linux中多线程保护,关于Linux下多线程情况下全局变量保护的问题,求个解决方案...

本文探讨了多线程编程中互斥锁与条件变量的使用,通过示例代码展示了如何在C语言中实现线程同步。文章指出,互斥锁在读写操作接近平衡时效率较高,而读写锁则适合读操作频繁的情况。同时,提到了使用信号量可能并不必要,因为访问全局变量前加锁互斥即可满足需求。
摘要由CSDN通过智能技术生成

要个效率高的方法

需附上全部源代码

|

这个比较全面了!

#include

#include

#include

pthread_mutex_t mutex;

pthread_cond_t  cond;

void * child1(void *arg)

{

pthread_cleanup_push(pthread_mutex_unlock,&mutex);

while(1){

printf("thread 1 get running n");

printf("thread 1 pthread_mutex_lock returns %dn",

pthread_mutex_lock(&mutex));

pthread_cond_wait(&cond,&mutex);

printf("thread 1 condition appliedn");

pthread_mutex_unlock(&mutex);

sleep(5);

}

pthread_cleanup_pop(0);

}

void *child2(void *arg)

{

while(1){

sleep(3);

printf("thread 2 get running.n");

printf("thread 2 pthread_mutex_lock returns %dn",

pthread_mutex_lock(&mutex));

pthread_cond_wait(&cond,&mutex);

printf("thread 2 condition appliedn");

pthread_mutex_unlock(&mutex);

sleep(1);

}

}

int main(void)

{

int tid1,tid2;

printf("hello, condition variable testn");

pthread_mutex_init(&mutex,NULL);

pthread_cond_init(&cond,NULL);

pthread_create(&tid1,NULL,child1,NULL);

pthread_create(&tid2,NULL,child2,NULL);

do{

sleep(2);                   /* comment 4 */

pthread_cancel(tid1);       /* comment 5 */

sleep(2);                   /* comment 6 */

pthread_cond_signal(&cond);

}while(1);

sleep(100);

pthread_exit(0);

}

有关于各种锁的效率的文章

http://www-128.ibm.com/developerworks/cn/linux/sdk/rt/part5/index.html

|

用POSIX 互斥锁比信号灯效率快20倍左右。

如果对全局变量的读、写操作差不多的话可以使用POSIX 互斥锁,可能回牺牲系统效率10%左右。

如果读操作比写操作要多的话可以使用读写锁。

互斥锁: pthread_mutex_lock   pthread_mutex_unlock

读写锁: pthread_rwlock_rdlock   pthread_rwlock_wrlock  pthread_rwlock_unlock

|

访问全部变量之前加锁互斥就可以了,用信号量没有必要啊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值