您的位置:首页 > 其它

线程同步——互斥量

2016-07-15 09:21 176 查看
互斥量的使用:

// 线程同步之互斥量
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>

using namespace std;

// 全局变量,两个线程都可以修改,因此修改的时候需要加锁
int g_Value = 0;

// 互斥量
pthread_mutex_t lock;

// 线程函数1
void* thread_func1(void* data)
{
int i = 0;
while(i < 10)
{
++i;

// 加锁
pthread_mutex_lock(&lock);
// 修改全局变量
++g_Value;
// 解锁
pthread_mutex_unlock(&lock);
}
return 0;
}

// 线程函数2
void* thread_func2(void* data)
{
int i = 0;
while(i < 10)
{
++i;
// 加锁
pthread_mutex_lock(&lock);
// 修改全局变量
++g_Value;
// 解锁
pthread_mutex_unlock(&lock);
}
return 0;
}

// 主函数
int main(int argc,char* argv[])
{
// 初始化互斥量
pthread_mutex_init(&lock,0);
// 定义两个线程id
pthread_t thd1,thd2;
// 创建两个线程
pthread_create(&thd1,0,thread_func1,0);
pthread_create(&thd2,0,thread_func2,0);

// 等待两个线程运行结束
pthread_join(thd1,0);
pthread_join(thd2,0);

// 销毁互斥量
pthread_mutex_destroy (&lock);

cout << g_Value<<endl;
return  0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: