【linux】pthread_mutex_t

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

int x = 0;

pthread_mutex_t mutex_x ;

void* client(void*data)
{
	pthread_mutex_lock(&mutex_x);

	fprintf(stdout,"%d:mutex_lock\n",data);

	++x;

	fprintf(stdout,"%d:mutex 正在修改x的值:%d\n",data,x);

	sleep(1);

	pthread_mutex_unlock(&mutex_x);

	fprintf(stdout,"%d:mutex_unlock\n",data);

}


int main(void)
{
	int i = 1;

	pthread_t threadInfo;
	pthread_attr_t threadInfo_attr;

	pthread_mutex_init(&mutex_x,NULL);

	pthread_create(&threadInfo,NULL,client,(void*)1);
	pthread_create(&threadInfo,NULL,client,(void*)2);
	pthread_create(&threadInfo,NULL,client,(void*)3);

	pthread_join(threadInfo,NULL);
	pthread_mutex_destroy(&mutex_x);
	
	fprintf(stdout,"Hi");

	return EXIT_SUCCESS;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
pthread_mutex_t是Linux线程中用于实现互斥锁的数据类型。它可以确保在多线程环境下对共享资源的访问是互斥的,避免了数据竞争的问题。 在使用pthread_mutex_t之前,需要先进行初始化。可以使用pthread_mutex_init函数进行初始化,该函数的原型如下: ```c int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); ``` 其中,mutex是要初始化的互斥量对象,attr是互斥量的属性,可以为NULL表示使用默认属性。 初始化完成后,可以使用pthread_mutex_lock函数对互斥量进行加锁,该函数的原型如下: ```c int pthread_mutex_lock(pthread_mutex_t *mutex); ``` 该函数会阻塞当前线程,直到成功获取到互斥量的锁。如果互斥量已经被其他线程锁定,则当前线程会被阻塞,直到互斥量被解锁。 另外,还可以使用pthread_mutex_trylock函数尝试对互斥量进行加锁,该函数的原型如下: ```c int pthread_mutex_trylock(pthread_mutex_t *mutex); ``` 该函数会尝试对互斥量进行加锁,如果互斥量已经被其他线程锁定,则函数会立即返回一个非零值,表示加锁失败。 最后,使用pthread_mutex_unlock函数对互斥量进行解锁,该函数的原型如下: ```c int pthread_mutex_unlock(pthread_mutex_t *mutex); ``` 该函数会解锁互斥量,允许其他线程获取到互斥量的锁。 总结起来,pthread_mutex_t是Linux线程中用于实现互斥锁的数据类型,通过pthread_mutex_init、pthread_mutex_lock、pthread_mutex_trylock和pthread_mutex_unlock等函数可以对互斥量进行初始化、加锁和解锁操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值