通过使用互斥量可以完成多线程间对变量的互斥访问。主要函数如下:
函数成功执行后,互斥锁被初始化为未锁住态。
当pthread_mutex_lock()返回时,该互斥锁已被锁定。线程调用该函数让互斥锁上锁,如果该互斥锁已被另一个线程锁定和拥有,则调用该线程将阻塞,直到该互斥锁变为可用为止。
int pthread_mutex_lock(pthread_mutex_t *mutex);
在成功完成之后会返回零。其他任何返回值都表示出现了错误。
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <iostream> #include <sys/syscall.h> /* 获得线程ID*/ using namespace std; #define NUM_Thread 6 int iThread_index; //获得线程ID pid_t gettid(void) { return syscall(SYS_gettid); } //线程调用函数 void *thread_func(void *arg); //线程互次变量 pthread_mutex_t work_mutex; int main() { int res; pthread_t a_thread[NUM_Thread]; pthread_mutex_init(&work_mutex,NULL); void *thread_result; iThread_index = 0; for(int iIndex = 0; iIndex < NUM_Thread; iIndex ++) { //创建线程 res = pthread_create(&a_thread[iIndex],NULL,thread_func,(void *)&iThread_index); if(0 != res) { perror("create thread failed\n"); exit(-1); } } printf("Waiting for thread to finish\n"); for(int iIndex = 0; iIndex < NUM_Thread; iIndex++) { //等待线程结束 res = pthread_join(a_thread[iIndex],&thread_result); if(0!= res) { printf("the %d thread failed\n",iIndex); } } pthread_mutex_destroy(&work_mutex); printf("press any key exit\n"); char c = getchar(); c = getchar(); } void *thread_func(void * arg) { printf("thread: %5u do something\n", gettid()); int rand_num =rand()%10; sleep(rand_num); printf("thread: %5u finish do something\n", gettid()); //互次变量加锁 pthread_mutex_lock(&work_mutex); int my_num = iThread_index; printf("the %d thread enter func\n",my_num); rand_num =rand()%10; sleep(rand_num); printf("the %d thread exit func\n",my_num); iThread_index++; //互次变量解锁 pthread_mutex_unlock(&work_mutex); pthread_exit(NULL); }
结果
administrator@ubuntu:~/桌面/Java/thread$ g++ threadmutex.cpp -o threadmutex -lpthread
administrator@ubuntu:~/桌面/Java/thread$ ./threadmutex thread: 3888 do something
thread: 3892 do something
thread: 3890 do something
thread: 3889 do something
Waiting for thread to finish
thread: 3891 do something
thread: 3893 do something
thread: 3888 finish do something
the 0 thread enter func
thread: 3891 finish do something
thread: 3890 finish do something
thread: 3893 finish do something
thread: 3892 finish do something
thread: 3889 finish do something
the 0 thread exit func
the 1 thread enter func
the 1 thread exit func
the 2 thread enter func
the 2 thread exit func
the 3 thread enter func
the 3 thread exit func
the 4 thread enter func
the 4 thread exit func
the 5 thread enter func
the 5 thread exit func
press any key exit
本文出自 “风清扬song” 博客,请务必保留此出处http://2309998.blog.51cto.com/2299998/1394544