1. 程式人生 > >Linux_執行緒的互斥鎖

Linux_執行緒的互斥鎖

功能:1、使多個執行緒可以互斥的訪問共享資源

            2、保護一段重要的程式碼,是這段程式碼在執行過程中,不會被打斷。

 

互斥鎖的操作:

1、定義一把互斥鎖

      pthread_mutex_t mutex;

2、對互斥鎖進行初始化

    1)靜態初始化 pthread_mutex_t mutex = PTHREAD_MUTEX_INITALIZER;

    2)動態初始化 int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);

3、在合適的地方加鎖

     int pthread_mutex_lock(pthread_mutex_t *mutex);                  //阻塞方式

     int pthread_mutex_trylock(pthread_mutex_t *mutex);             //非阻塞方式

4、在合適的地方解鎖

     int pthread_mutex_unlock(pthread_mutex_t *mutex);

5、銷燬互斥鎖,釋放資源

     int phtread_mutex_destroy(pthread_mutex_t *mutex);

 

一般不要定義全域性變數,此處是為了節省,我們可以把全域性變數放在標頭檔案中,保證資料呼叫安全。

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

int a;
int b;
int count;

pthread_mutex_t mutex;

void *thread_func1(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);
		a = count;
		b = count;
		pthread_mutex_unlock(&mutex);
		count++;
	}
}

void *thread_func2(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);
		if(a != b)
		{
			printf("a和b不相等,a = %d, b = %d\n", a, b);
		}
		pthread_mutex_unlock(&mutex);
	}
}

int main(void)
{
	pthread_t tid1;
	pthread_t tid2;
	int ret;
	pthread_mutex_init(&mutex, NULL);
	ret = pthread_create(&tid1, NULL, thread_func1, NULL);
	ret += pthread_create(&tid2, NULL, thread_func2, NULL);

	if(ret != 0)
	{
		perror("pthread_create");
		exit(1);
	}

	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);

	return 0;
}