I am learning about threads in POSIX. I can create a thread that runs a function. But my goal is to have a lot of threads that each has it's own ID-variable that it can use (this is the reason why I chosed threads, it was between threads and forks).
But now the problem is that each thread waits for the other to run. I tried to remove "pthread_join()" but then only one thread ran. Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *t_func(void*);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int main() {
pthread_t th1, th2;
int iret1, iret2;
iret1 = pthread_create(&th1, NULL, t_func, (void*)100);
iret2 = pthread_create(&th2, NULL, t_func, (void*)3);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
printf("done\n");
exit(0);
}
void *t_func(void *tmp) {
int n = (int)tmp;
printf("#%d starting\n", n);
printf("#%d ending\n", n);
}
I want the two threads to run at the same time, so the output would be:
Code:
#100 starting
#3 starting
#100 ending
#3 ending
done
As I said, now the threads run after each other (starting, ending the first, starting, ending the second). And when I removed "pthread_join" I got "starting, ending the first" and then the program stopped. The second thread didn't run.