pthread_mutex_trylock和pthread_mutex_lock问题(没有加锁???)
#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
输出的结果有点诡异,像是没有加锁,求解释。。。