sometimesnever
sometimesnever

Reputation: 9

Thread immediately executes after pthread_create?

When I'm creating T threads, I have the following code in the main thread.

pthread_t threads[T];
for (a=0; a<T; a++) {
    pthread_create(&(threads[a]), NULL, foo(threads, locks, transition), NULL);
}
printf("in main thread\n");

It creates the first thread, and I noticed that it immediately begins executing the first thread. foo is called for the first thread and "in main thread" gets outputed after. My actual intent was to create all T threads first (pushing the threads into a 'ready' queue) and then continue executing code in the main thread until it exits or yields. Once main exits, I want one of the T threads to execute.

In foo function:

void foo(pthread_t *threads, pthread_mutex_t **locks, double **transition) {
    printf("in foo\n");
}

In the main_thread function:

void main_thread (int *N, int *T) {
    double **transition;
    pthread_mutex_t **locks;

    transition = malloc(*N * sizeof *transition);
    locks = malloc(*N * sizeof *locks);
    for (a=0; a< *N; a++) {
        transition[a] = malloc(*N * sizeof *transition[a]);
        locks[a] = malloc(*N * sizeof *locks[a]);
    }

    // lock for each element in transition matrix
    for (a=0; a<*N; a++) {
        for (b=0; b<*N; b++) {
            if (pthread_mutex_init(&(locks[a][b]), NULL) != 0) { 
                printf("\n mutex init has failed\n"); 
            }
        }
    }

    for (a=0; a<*N; a++) {
        for (b=0; b<*N; b++) {
            transition[a][b] = 0.0;
        }
    }

    pthread_t threads[T];
    for (a=0; a<T; a++) {
        pthread_create(&(threads[a]), NULL, foo(threads, locks, transition), NULL);
    }
    printf("in main thread\n");


}

In the main function:

int main(int argc, char *argv[]) {

    int N = 4;
    int T = 2;

    pthread_t main_t;
    pthread_create(&main_t, NULL, &main_thread(&N, &T), NULL); 

    return 0;
}

Upvotes: 1

Views: 1794

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

With foo(...) you call the function, passing the result of it to the pthread_create function. That means the function will execute before any thread is created.

You need to pass a pointer to the thread function instead:

pthread_create(&threads[a], NULL, foo, NULL);

Also note that when the main function exits, it usually leads to the whole process exiting and that will kill all threads you have started.

If you want to keep threads running after you exit the main thread then you need to use pthread_exit from the main thread, and detach the threads you create.

And to not start the threads at once, IIRC there are attributes you can set and pass to the pthread_create function (the second argument) to start the threads as suspended. You have to explicitly resume the threads though, that won't happen automatically.

Upvotes: 2

Related Questions