pthread_mutex_trylock和pthread_mutex_lock问题(没有加锁???)

fuxavier 2011-07-21 10:32:02
#include<iostream>
#include<pthread.h>
#include<string.h>
#include<stdio.h>

using namespace std;
pthread_mutex_t q_lock=PTHREAD_MUTEX_INITIALIZER;
void *read(void *arg)
{
int err=0;
while((err=pthread_mutex_trylock(&q_lock))!=0)
{
cout <<"read :"<< strerror(err) << endl;
}

/*err=pthread_mutex_lock(&q_lock);
if(err!=0)
{
cout << "error " << endl;
};
*/
cout << "first " << endl;
for(int i = 0;i<=5;i++)
cout << " " << i << endl;
err=pthread_mutex_unlock(&q_lock);
if(err!=0)
{
cout << "wrong " <<endl;
}
};
void *read1(void *arg)
{ int err=0;
while((err=pthread_mutex_trylock(&q_lock))!=0)
{
cout <<"read1:"<< strerror(err) <<endl;
}
/* err = pthread_mutex_trylock(&q_lock);
if(err == EBUSY)
{
cout << "busy " << endl;
}
*/
cout << "second " << endl;
for(int i = 0;i<=5;i++)
cout << " " << i << endl;
err=pthread_mutex_unlock(&q_lock);
if(err!=0)
{
cout << "wrong " <<endl;
}
}
int main()
{
pthread_t id1,id2;
int ret;

ret=pthread_create(&id1,NULL,read, NULL);
if(ret!=0)perror("pthread cread1");


ret=pthread_create(&id2,NULL,read1, NULL);
if(ret!=0)perror("pthread cread2");

pthread_join(id1,NULL);
pthread_join(id2,NULL);


return 0;

}
输出结果为:
first read1:Device or resource busy

read1:Device or resource busy
read1:Device or resource busy
....
..
..
..

read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
0
1
2
3
4
read1: 5
Device or resource busy
second
0
1
2
3
4
5
输出的结果有点诡异,像是没有加锁,求解释。。。
...全文
620 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2011-07-21
  • 打赏
  • 举报
回复
改用write替代cout试一试把.
louyong0571 2011-07-21
  • 打赏
  • 举报
回复
结果看来是正常的啊,first先锁了,0-5输出完了以后释放锁,然后second才往下跑,很正常啊
yong_f 2011-07-21
  • 打赏
  • 举报
回复
这个说明已经加锁了,

first输出这个的时候以前是第一线程在运行,这时候跳到第二个线程 read1:Device or resource busy

read1:Device or resource busy
read1:Device or resource busy
....
..
..
..

read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy
read1:Device or resource busy //这时候第二个线程运行结束,跳到第一个线程
0
1
2
3
4
read1: 5//第一个线程释放锁
Device or resource busy//第二个线程运行
//获得锁second
0
1
2
3
4
5
运行结束。

4,465

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 内核源代码研究区
社区管理员
  • 内核源代码研究区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧