LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   About POSIX threads (https://www.linuxquestions.org/questions/programming-9/about-posix-threads-262087/)

Ephracis 12-03-2004 05:49 AM

About POSIX threads
 
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.

Marius2 12-03-2004 06:33 AM

The second thread doesn't wait for the first. It's just that thread 1 doesn't exist
long enough to be still there when thread 2 is created. Modify your thread function
like this:

void *t_func(void *tmp) {
int n = (int)tmp;
int c=0;
printf("#%d starting\n", n);
while(c++<10000){
printf(#%d doing something\n");
usleep(1000*50);
}
printf("#%d ending\n", n);
}


HTH


All times are GMT -5. The time now is 01:02 PM.