# Call blocking C function

**URL:** <https://discourse.julialang.org/t/call-blocking-c-function/69427>\
**Category:** General Usage\
**Created:** [October 8, 2021, 10:11am UTC](https://discourse.julialang.org/t/call-blocking-c-function/69427 "2021-10-08T10:11:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mikhail\_Kagalenko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikhail_kagalenko/32/13257_2.png) [@Mikhail\_Kagalenko](https://discourse.julialang.org/u/Mikhail_Kagalenko)\
**Post date:** [October 8, 2021, 10:11am UTC](https://discourse.julialang.org/t/call-blocking-c-function/69427/1 "2021-10-08T10:11:44Z")

</div>

I am trying to create a task that asynchronously accepts connection on a TCP socket initialized by external C code, something like this (simplified):

```julia
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int make_socket(int port)
{
  struct sockaddr_in addr = {0};
  int sck = socket(AF_INET, SOCK_STREAM, 0);
  addr.sin_family = AF_INET;
  addr.sin_port = htons(port);
  addr.sin_addr.s_addr = htonl(INADDR_ANY);
  bind(sck, (struct sockaddr *)&addr, sizeof(addr));
  listen(sck, 1);

  return sck;
}

```

Then I use this from Julia as follows:

```julia
new_sock(port) =ccall((:make_socket, "libtmp"), Cint, (Cint,), port)
mutable struct Sockaddr end
socket_accept(sockfd) = begin s_addr=Sockaddr();addr_len=Clonglong(0); ccall(:accept, Cint,(Cint,Ptr{Cvoid}, Ptr{Clonglong}),sockfd,Ref(s_addr),Ref(addr_len)); addr_len;end

```

The problem is that `socket_accept()` blocks until a connection is made to the port. As far as I understand the problem, Julia threads use cooperative multitasking. So Base.Threads macro `@spawn` and Distributed’s task creation macro `@spawnat` do not return until the connection is made to the port. Is there some method to create a listener process that would not block Julia REPL?

(I know about Julia’s Sockets module, but need to use an externally created socket)

---

<div class="post-metadata">

**Author:** ![Jeff\_Emanuel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeff_emanuel/32/15440_2.png) [@Jeff\_Emanuel](https://discourse.julialang.org/u/Jeff_Emanuel)\
**Post date:** [October 8, 2021, 1:58pm UTC](https://discourse.julialang.org/t/call-blocking-c-function/69427/2 "2021-10-08T13:58:59Z")

</div>

Check `Threads.nthreads()`

---

<div class="post-metadata">

**Author:** ![Mikhail\_Kagalenko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikhail_kagalenko/32/13257_2.png) [@Mikhail\_Kagalenko](https://discourse.julialang.org/u/Mikhail_Kagalenko)\
**Post date:** [October 8, 2021, 2:43pm UTC](https://discourse.julialang.org/t/call-blocking-c-function/69427/3 "2021-10-08T14:43:10Z")

</div>

Wow, this is it, thanks! Somewhat embarrassing mistake, to be sure.
