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;
}

猜你喜欢

转载自blog.csdn.net/weixin_40878111/article/details/84825843
今日推荐