What I've noticed recently in attempting to add some multithreaded functionality to some code of mine for a project at work is that pthreads are a huge pain in the ass to deal with logistically...
Here's the scenario...
I have an infinite loop in my main method (a server) spawning threads to deal with data whenever it receives a packet from whatever client. The problem is that I can't get the threads to execute concurrently at all. They refuse to begin execution until a call to pthread_join() from the main method, which completely kills the whole purpose of using threads in the first place (server needs to STOP execution flow, and wait for the thread to finish processing its data before receiving anymore packets! ridiculous.)
So is there a way to use pthreads and have them actually be multithreaded? Or am I better off not using threads at all, and saving the extra resources by stopping execution in my server to call a function to process data?
I'm thinking I may have to resort to forking everytime...
This is frustrating....
some sample code i did is below:
// gcc threads.c -lpthread
#include <stdio.h>
#include <pthread.h>
struct point{
int x, y;
};
static void *print_point(void *point_p);
int main() {
pthread_t tid;
struct point pt = {3, 5};
printf("enter main\n");
pthread_create(&tid, NULL, print_point, &pt);
while(1){continue;}
return 0;
}
static void *print_point(void *point_p) {
struct point arg = * (struct point *) point_p;
printf("Point: (%d, %d)\n", arg.x, arg.y);
return NULL;
}
when I run and compile that (yes i compile with the -lpthread switch), it prints "enter main" and doesn't execute the thread... I even let it run for a while (got up, went to the bathroom, ate some food), and still nothing.
So since the main method spawns a thread then loops infinitely, the thread should eventually execute... right? From what I can tell from my tests the main method never gives up execution to the thread it spawned. The only way I can get it to give it up it by calling join (but that defeats the purpose of having threads since main will wait around until the thread is done).