最近喜欢听大学听到的老歌,deutschland 德国世界杯时候流行的,据说不是主题曲但是比主题曲还要火。
本篇进入难点了,mutex互斥锁概念,mutex=mutual exclusion的缩写,顺便说一句:以前老师都爱用缩写,也不跟同学说全称,这尼玛能理解深刻么!下文是用法:
#include <iostream> #include <pthread.h>//按规矩不能少 using namespace std; #define NUM_THREADS 5 int sum = 0;//定义个全局变量,让所有线程进行访问,这样就会出现同时写的情况,势必会需要锁机制; pthread_mutex_t sum_mutex; void* say_hello(void* args) { cout << "hello in thread " << *((int *)args) << endl; pthread_mutex_lock (&sum_mutex);//修改sum就先加锁,锁被占用就阻塞,直到拿到锁再修改sum; cout << "before sum is " << sum << " in thread " << *((int *)args) << endl; sum += *((int *)args); cout << "after sum is " << sum << " in thread " << *((int *)args) << endl; pthread_mutex_unlock (&sum_mutex);//完事后解锁,释放给其他线程使用; pthread_exit(0);//退出随便扔个状态码 } int main() { pthread_t tids[NUM_THREADS]; int indexes[NUM_THREADS]; //下三句是设置线程参数没啥可说的 pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init (&sum_mutex, NULL);//这句是对锁进行初始化,必须的; for(int i = 0; i < NUM_THREADS; ++i) { indexes[i] = i; int ret = pthread_create( &tids[i], &attr, say_hello, (void *)&(indexes[i]) );//5个进程去你们去修改sum吧哈哈; if (ret != 0) { cout << "pthread_create error: error_code=" << ret << endl; } } pthread_attr_destroy(&attr);//删除参数变量 void *status; for (int i = 0; i < NUM_THREADS; ++i) { int ret = pthread_join(tids[i], &status); if (ret != 0) { cout << "pthread_join error: error_code=" << ret << endl; } } cout << "finally sum is " << sum << endl; pthread_mutex_destroy(&sum_mutex);//注销锁,可以看出使用pthread内置变量神马的都对应了销毁函数,估计是内存泄露相关的吧; }
惯例:g++ -lpthread -o ex_mutex ex_mutex.cpp
运行:
hello in thread 4 before sum is 0 in thread 4 after sum is 4 in thread 4 hello in thread 3 before sum is 4 in thread 3 after sum is 7 in thread 3 hello in thread 2 before sum is 7 in thread 2 after sum is 9 in thread 2 hello in thread 1 before sum is 9 in thread 1 after sum is 10 in thread 1 hello in thread 0 before sum is 10 in thread 0 after sum is 10 in thread 0 finally sum is 10
发现个现象,thread4先运行,很诡异吧而i是从0递增的,所以呢多线程的顺序是混乱的,混乱就是正常;只要sum访问及修改是正常的,就达到多线程的目的了,运行顺序不能作为参照;