您的位置:首页 > 其它

线程同步---互斥量mutex

2015-08-02 22:07 183 查看
1. 问题引入:开两个线程同时对一个全局变量10万次做自加,结果会如何?

#include <stdio.h>
#include <string.h>
#include <pthread.h>

unsigned int g_cn = 0;

void* thread_proc (void* arg) {
	unsigned int i;
	for (i = 0; i < 100000; i++)
		++g_cn;

	return NULL;
}

int main (void) {
	size_t i;
	pthread_t tids[2];
	int error;

	for (i = 0; i < sizeof (tids) / sizeof (tids[0]); i++)
		if ((error = pthread_create (&tids[i], NULL, thread_proc,
			NULL)) != 0) {
			fprintf (stderr, "pthread_create: %s\n", strerror (error));
			return -1;
		}

	for (i = 0; i < sizeof (tids) / sizeof (tids[0]); i++)
		if ((error = pthread_join (tids[i], NULL)) != 0) {
			fprintf (stderr, "pthread_join: %s\n", strerror (error));
			return -1;
		}

	printf ("g_cn = %u\n", g_cn);
	return 0;
}



思考:多执行几次,结果很神奇吧,那么为什么有的时候会出现结果不是20万呢,其实质原因是加法不是原子操作。加法对应的汇编指令至少分为读内存,算加法,写内存三步,而线程的切换可能发生在任何一步,这就引起当一个线程还没完成加法,另一个线程在这个不准确的基础上做了一次加法,结果自然会比正确结果小。而且线程切换的次数越多结果就越不准确,这就需要我们建立一种同步机制来保证数据的可靠性。

2. 互斥量机制:其实质就是加锁解锁

nt pthread_mutex_init (pthread_mutex_t* mutex,const pthread_mutexattr_t* mutexattr);//初始化函数

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;(和初始化函数的效果一样)

int pthread_mutex_lock (pthread_mutex_t* mutex);

int pthread_mutex_unlock (pthread_mutex_t* mutex);

int pthread_mutex_destroy (pthread_mutex_t* mutex);


编程模型:

1) 互斥量被初始化为非锁定状态;

2) 线程1调用pthread_mutex_lock函数,立即返回,互斥量呈锁定状态;

3) 线程2调用pthread_mutex_lock函数,阻塞等待;

4) 线程1调用pthread_mutex_unlock函数,互斥量呈非锁定状态;

5) 线程2被唤醒,从pthread_mutex_lock函数中返回,互斥量呈锁定状态;

#include <stdio.h>
#include <string.h>
#include <pthread.h>

unsigned int g_cn = 0;
/*
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
*/
pthread_mutex_t g_mtx;

void* thread_proc (void* arg) {
	unsigned int i;
	for (i = 0; i < 100000; i++) {
		pthread_mutex_lock (&g_mtx);
		++g_cn;
		pthread_mutex_unlock (&g_mtx);
	}

	return NULL;
}
	
int main (void) {
	size_t i;
	pthread_t tids[2];
	int error;

	pthread_mutex_init (&g_mtx, NULL);

	for (i = 0; i < sizeof (tids) / sizeof (tids[0]); i++)
		if ((error = pthread_create (&tids[i], NULL, thread_proc,
			NULL)) != 0) {
			fprintf (stderr, "pthread_create: %s\n", strerror (error));
			return -1;
		}

	for (i = 0; i < sizeof (tids) / sizeof (tids[0]); i++)
		if ((error = pthread_join (tids[i], NULL)) != 0) {
			fprintf (stderr, "pthread_join: %s\n", strerror (error));
			return -1;
		}

	pthread_mutex_destroy (&g_mtx);
	printf ("g_cn = %u\n", g_cn);
	return 0;
}
能保证结果每次都是20万。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: