详解Linux多线程编程(不限Linux)

2019-10-13 14:05:59丽君

这样就完成了1)、2)、3)这三点要求。编译执行得如下结果:

netsky@ubuntu:~/workspace/pthead_test$ gcc -lpthread test.c 

如果程序中使用到了pthread库中的函数,除了要#include<pthread.h>,在编译的时候还有加上-lpthread 选项。

netsky@ubuntu:~/workspace/pthead_test$ ./a.out 
enter main 
enter thread2 
this is thread2, g_Flag: 0, thread id is 3079588720 
this is thread1, g_Flag: 2, thread id is 3079588720 
leave thread2 
leave main 
enter thread1 
this is thread1, g_Flag: 2, thread id is 3071196016 
this is thread1, g_Flag: 1, thread id is 3071196016 
leave thread1 

但是运行结果不一定是上面的,还有可能是:

netsky@ubuntu:~/workspace/pthead_test$ ./a.out 
enter main 
leave main 
enter thread1 
this is thread1, g_Flag: 0, thread id is 3069176688 
this is thread1, g_Flag: 1, thread id is 3069176688 
leave thread1 

或者是:

netsky@ubuntu:~/workspace/pthead_test$ ./a.out 
enter main 
leave main 

等等。这也很好理解因为,这取决于主线程main函数何时终止,线程thread1、thread2是否能够来得急执行它们的函数。这也是多线程编程时要注意的问题,因为有可能一个线程会影响到整个进程中的所有其它线程!如果我们在main函数退出前,sleep()一段时间,就可以保证thread1、thread2来得及执行。

Attention:大家肯定已经注意到了,我们在线程函数thread1()、thread2()执行完之前都调用了pthread_exit。如果我是调用exit()又或者是return会怎样呢?自己动手试试吧!

pthread_exit()用于线程退出,可以指定返回值,以便其他线程通过pthread_join()函数获取该线程的返回值。 return是函数返回,只有线程函数return,线程才会退出。 exit是进程退出,如果在线程函数中调用exit,进程中的所有函数都会退出!

“4) 线程序1需要在线程2退出后才能退出”第4点也很容易解决,直接在thread1的函数退出之前调用pthread_join就OK了。

4、线程之间的互斥

上面的代码似乎很好的解决了问题的前面4点要求,其实不然!!!因为g_Flag是一个全局变量,线程thread1和thread2可以同时对它进行操作,需要对它进行加锁保护,thread1和thread2要互斥访问才行。下面我们就介绍如何加锁保护——互斥锁。

互斥锁:

使用互斥锁(互斥)可以使线程按顺序执行。通常,互斥锁通过确保一次只有一个线程执行代码的临界段来同步多个线程。互斥锁还可以保护单线程代码。

互斥锁的相关操作函数如下:

#include <pthread.h> 

int pthread_mutex_lock(pthread_mutex_t * mptr); 
int pthread_mutex_unlock(pthread_mutex_t * mptr); 
//Both return: 0 if OK, positive Exxx value on error