线程互斥
现在想让线程一个一个执行,那么就要用到线程间互斥:
1 #include <stdio.h> 2 #include <pthread.h> 3 #include <unistd.h> 4 5 pthread_mutex_t mutex; //线程互斥锁 6 7 void init() 8 { 9 pthread_mutex_init(&mutex ,NULL)//初始化线程互斥锁 10 } 11 12 void printer(char *str) 13 { 14 pthread_mutex_lock(&mutex);//将该函数锁住,不允许其他线程调用 15 while(*str != '\0') 16 { 17 putchar(*str); 18 fflush(stdout); 19 str ++; 20 sleep(1); 21 } 22 pthread_mutex_unlock(&mutex);//函数解锁,允许其他线程调用该函数 23 } 24 25 void *thread_fun_1(void *arg) 26 { 27 char *str = "lan"; 28 printer(str); 29 } 30 31 void *thread_fun_2(void *arg) 32 { 33 char *str = "shanxiao"; 34 printer(str); 35 } 36 37 int main() 38 { 39 init(); 40 41 pthread_t tid1,tid2; 42 43 pthread_create(&tid1, NULL, thread_fun_1, NULL);//创建线程1 44 pthread_create(&tid2, NULL, thread_fun_2, NULL);//创建线程2 45 46 pthread_join(tid1, NULL);//执行线程1 47 pthread_join(tid2, NULL);//执行线程2 48 49 return 0; 50 }
pthread_create() 可查看此网页:http://baike.baidu.com/item/pthread_create?fr=aladdin
pthread_join() 可查看此网页:http://baike.baidu.com/item/pthread_join?sefr=cr
pthread_mutex_lock()和pthread_mutex_unlock()百度查看。
上面的代码在Linux系统下的编译器执行,命令为:gcc 文件名.c -lpthread -o 文件名。比如:gcc printer.c -lpthread -o printer。
Windows系统下没有试过命令行编译,有兴趣的朋友可以试一试,知道怎样做的朋友可以在评论区中回复我,谢谢!