Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wrote this brief example in order to understand thread programming in C.It was supposed to write "thread 0". But there is no output. Here is the code.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int i=0;
pthread_mutex_t mutex;

void * fonction(){
    pthread_mutex_lock(&mutex);
    printf("thread %d 
",i++);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main(){
    pthread_t a;
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&a,NULL,fonction,NULL);
    return EXIT_SUCCESS;
}

Can someone help me ? Ps : I used this to compile it

gcc -pthread test.c -o test
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

Insert pthread_join(a, NULL) after pthread_create() and before return EXIT_SUCCESS; to ensure the child thread is finished before main() returns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...