Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2235919
  • 博文数量: 292
  • 博客积分: 10016
  • 博客等级: 中将
  • 技术积分: 3381
  • 用 户 组: 普通用户
  • 注册时间: 2005-11-06 11:26
文章分类

全部博文(292)

文章存档

2011年(1)

2010年(4)

2009年(3)

2008年(6)

2007年(47)

2006年(63)

2005年(168)

分类: LINUX

2008-04-14 00:35:55

 

#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>


//此程序加入了互斥锁

//父子线程是并行,没有一定的顺序

//所以如果父线程加锁,子线程没有可用的资源,你们程序就退出

//如果子线程加锁,父线程没有可用资源,那么程序将会进入等待解锁状态,导致程序不能正常结束.


static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t ntid;

void printids(const char *s)
{
pid_t pid;
pthread_t tid;

pid = getpid(); //进程ID

tid = pthread_self(); //线程ID


pthread_mutex_lock(&mutex);

printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,(unsigned int)tid,(unsigned
int)tid);

//下面这行进行注释也就是只加锁,不解锁,测试程序。

pthread_mutex_unlock(&mutex);

}

void *thr_fn(void *arg)
{
printids("new thread:");
return ((void *)0);
}


int main()
{
int err;

err = pthread_create(&ntid,NULL,thr_fn,NULL);
if(err != 0)
{
printf("can't create thread: %s\n",strerror(err));
return 1;
}

printids("main thread:");

return 0;
}

阅读(3828) | 评论(3) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2008-04-18 16:13:37

竞争了! main里面join一下!

blueday2008-04-18 00:04:29

如果需要声明特定属性的互斥锁,须调用函数pthread_mutexattr_init。

jjlc2008-04-17 09:55:00

写了static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 是不是在main函数里面就不用init互斥锁了呢?