Reputation: 3425
I am writing a C program that forks once it accepts a client connection. Once this happens, I want to spawn two threads, but I cannot seem to get this working.
pthread_t t1, t2;
void *r_loop();
void *w_loop();
.
.
.
sockfd = accept(r_sockfd, (struct sockaddr *) &address, &len);
if (sockfd < 0)
printf("Error accepting\n");
if (!fork())
{
int r_thread = pthread_create(&t1, NULL, r_loop, NULL);
int w_thread = pthread_create(&t2, NULL, w_loop, NULL);
pthread_join(r_thread, NULL);
pthread_join(w_thread, NULL);
exit(0);
}
When I run this, the functions r_loop and w_loop don't get executed.
Upvotes: 2
Views: 496
Reputation: 91
you should pass t1
and t2
instead of r_thread
and w_thread
to pthread_join()
.
Upvotes: 1
Reputation: 1606
The problem could be this: pthread_create() on success alwasy returns zero. You are passing to pthread_join() an incorrect value (that is zero instead of t1 and t2) making them to return immediately. Then the following exit() also kills the new starting threads
Upvotes: 5