不解的线程和互斥
来源:互联网 发布:php高级工程师工资 编辑:程序博客网 时间:2024/05/21 05:18
http://topic.csdn.net/u/20070705/19/cd743d75-8bf9-4bc9-94cb-9d479033bf00.html
环境:ubuntu6.06+gcc4.0.3
关于pthread_mutex_trylock我是这样理解的:这个函数尝试锁住互斥体变量,如果互斥体没有上锁,那么加锁,否则返回一个消息,这样可以防止死锁的产生。
可是在我测试的时候发现它根本不能锁住变量,请大家看一下是我那里写错了。
#include <pthread.h>
#include <stdio.h>
int ggg;
pthread_mutex_t mut1; //= PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mut2;
void *fun1(void *str)
{
unsigned int s;
s = pthread_self();
int p;
while(1)
{
if (!pthread_mutex_trylock(&mut1))
{
//sleep(1);
if (!pthread_mutex_trylock(&mut2))
{ ggg = s % 1000;
printf( "fun111 %d pth :: %u --> ggg is %d\n ", (int)str, s, ggg);
sleep(1);
printf( "fun111 %d pth :: %u **> ggg is %d\n ", (int)str, s, ggg);
pthread_mutex_unlock(&mut1);
pthread_mutex_unlock(&mut2);
return 0;
}else
{
//printf( "fun111 mut2 %d pth :: %u\n ", (int)str, s);
pthread_mutex_unlock(&mut2);
usleep(1000);
}
}else
{//printf( "fun111 mut1 %d pth :: %u\n ", (int)str, s);
pthread_mutex_unlock(&mut1);
usleep(1000);
}
}
}
void *fun2(void *str)
{
unsigned int s;
s = pthread_self();
int p;
while(1)
{
if (!pthread_mutex_trylock(&mut2))
{
//sleep(2);
if (!pthread_mutex_trylock(&mut1))
{ ggg = s % 1000;
printf( "fun222 %d pth :: %u --> ggg is %d\n ", (int)str, s, ggg);
sleep(1);
printf( "fun222 %d pth :: %u **> ggg is %d\n ", (int)str, s, ggg);
pthread_mutex_unlock(&mut2);
pthread_mutex_unlock(&mut1);
return 0;
}else
{//printf( "fun222 mut1 %d pth :: %u\n ", (int)str, s);
pthread_mutex_unlock(&mut1);
usleep(1000);
}
}else
{//printf( "fun222 mut2 %d pth :: %u\n ", (int)str, s);
pthread_mutex_unlock(&mut2);
usleep(1000);
}
}
}
int main()
{
int i;
pthread_t pthid[100];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&mut2, NULL);
pthread_mutex_init(&mut1, NULL);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for (i = 0; i < 3; ++i)
{
pthread_create(&pthid[i], &attr, fun1, (void*)i);
pthread_create(&pthid[i+20], &attr, fun2, (void*)(i+20));
//pthread_join(pthid[i], NULL);
}
sleep(100);
}
- 不解的线程和互斥
- windows的线程互斥和同步
- 线程间的同步和互斥
- 线程的同步和互斥
- Linux线程的同步和互斥
- python 线程的同步和互斥
- 一个线程和互斥的例子
- 线程的互斥和同步
- 线程之间的互斥和同步
- 线程之间的互斥和同步
- 线程之间的同步和互斥
- win32 线程的互斥和同步
- 线程的互斥
- 线程的互斥
- 线程的互斥
- 线程的互斥
- 线程的互斥
- 线程的互斥
- jCountdown倒计时插件 基于jquery开发的插件
- Swing模型与渲染器
- linux进程间通讯
- 8个HDFS的替代方案
- Android照相机俩种常见的使用方式(二)
- 不解的线程和互斥
- httpclient 3中超时
- 数据之魅:基于开源工具的数据分析
- jsp九大内置对象
- Windows系统不同SVN版本对比
- 常用正则表达式例子
- iphone-- UIView 加入边框,阴影,圆角
- Android驱动中的Kconfig文件与Makefile文件件
- 简明 Vim 练级攻略(转)