直接上个例子几简单哦!
现在我姑且认为互斥锁就是为了保护共享变量(现在看到的这个共享变量就是全局变量)而设置的,因为还没学那么多。
//互斥锁的使用
#include<errno.h>
#include< cstring>
#include< iostream>
#include< cstdlib>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include< ctime>
#include<arpa/inet.h>
using namespace std;
const int NLOOP=10;
int counter,n; //在这里counter就是那个我想保护的共享变量罗
void std_err(string s)
{
cout<<s<<"failed"<<endl;
exit(0);
}
pthread_mutex_t counter_mutex=PTHREAD_MUTEX_INITIALIZER; //互斥锁变量设置为静态分配的
void* doit(void* vptr)
{
int i,val;
for(i=0;i<NLOOP;i++)
{
sleep(1);
n=pthread_mutex_lock(&counter_mutex); //为互斥锁counter_mutex上锁,在操作全局变量conuter之前必须上锁
if(n!=0)
std_err("pthread_mutex_lock");
val=counter;
cout<<pthread_self()<<":"<<val+1<<endl;
n=pthread_mutex_unlock(&counter_mutex); //为互斥变量counter_mutex解锁
if(n!=0)
std_err("pthread_mutex_unlock");
}
return NULL;
}
int main()
{
pthread_t tidA,tidB;
n=pthread_create(&tidA,NULL,doit,NULL); //创建次线次
if(n!=0)
std_err("pthread_create");
n=pthread_create(&tidB,NULL,doit,NULL); //创建第二个次线次
if(n!=0)
std_err("pthread_createB");
n=pthread_join(tidA,NULL);
if(n!=0)
std_err("pthread_join");
n=pthread_join(tidB,NULL);
if(n!=0)
std_err("pthread_joinB");
return 0;
}
栗子呢是来自unix网络编程p554,我不会,就照着写,当然比他那个好看一些。栗子的结果为也上一张图片巴。