您的位置:首页 > 编程语言 > C语言/C++

【工作笔记】互斥锁

2017-02-22 15:42 363 查看

代码说明

当代码中出现多个线程需要操作一个同一个变量时,需要互斥锁。下面的代码实现了,globVar增加200000次,一个线程增加10000次。互斥锁保证globVar是20000。代码在DEV C++上测试通过。

代码实例

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>

void *thread_function(void *arg);
void *thread_function1(void *arg);
void *thread_function2(void *arg);

long long globVar = 0;

pthread_t a_thread;
pthread_t thread1;
pthread_t thread2;

/* 互斥锁 */
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

int main()
{
int res = 0;
int *pRet;

/* 创建新线程1 */
res = pthread_create(&thread1, NULL, thread_function1, NULL);
if (res != 0)
{
perror("Thread creation failed");
exit(EXIT_FAILURE);
}

/* 创建新线程2 */
res = pthread_create(&thread2, NULL, thread_function1, NULL);
if (res != 0)
{
perror("Thread creation failed");
exit(EXIT_FAILURE);
}

/* 线程阻塞 */
pthread_join(thread1, &pRet);
pthread_join(thread2, &pRet);

/* 打印最后的globVar值 */
printf("globVar=%d", globVar);

return 0;
}

void *thread_function1(void *arg)
{
int i = 1;
int locVar=0;
for (i = 1; i <= 10000; i++)
{
/* 上锁 */
pthread_mutex_lock(&mtx);

globVar++;

/* 解锁 */
pthread_mutex_unlock(&mtx);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 函数 线程