LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1232|回复: 9

linux下多线程问题

[复制链接]
发表于 2009-8-15 21:43:02 | 显示全部楼层 |阅读模式
/* example.c*/
  #include <stdio.h>
  #include <pthread.h>
  void thread(void)
  {
  int i;
  for(i=0;i<3;i++)
  printf("This is a pthread.\n");
  }
  int main(void)
  {
  pthread_t id;
  int i,ret;
  ret=pthread_create(&id,NULL,(void *) thread,NULL);
  if(ret!=0){
  printf ("Create pthread error!\n");
  exit (1);
  }
  for(i=0;i<3;i++)
  printf("This is the main process.\n");
  pthread_join(id,NULL);
  return (0);
  }
  我们编译此程序:
  gcc example1.c -lpthread -o example1
  运行example1,我们得到如下结果:
  This is the main process.
  This is a pthread.
  This is the main process.
  This is the main process.
  This is a pthread.
  This is a pthread.
这是在网上找的一个例子,但这个例子在我的fc8上运行结果却是
    This is a pthread.
    This is a pthread.
    This is a pthread.
    This is the main process.
    This is the main process.
    This is the main process.
这是为什么阿?
发表于 2009-8-15 23:15:33 | 显示全部楼层
我能想到的解释是,你的机器比作者的机器快太多了
在线程切换前,printf就执行完了
哈哈
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-8-16 09:55:58 | 显示全部楼层
这个代码在网上的,我觉得应该是对的 ,不知道这是跟cpu调度有关 还是什么 希望大虾来看一下
回复 支持 反对

使用道具 举报

发表于 2009-8-16 10:36:40 | 显示全部楼层
线程之间异步执行,任何结果都有可能。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-8-16 21:32:48 | 显示全部楼层
没人知道么 详解一下 这个无法控制么 想得到例子中的结果该如何呢?
回复 支持 反对

使用道具 举报

发表于 2009-8-17 13:23:21 | 显示全部楼层
想得到例子中的结果嘛,你可以在每个printf后面加 sleep(1);
回复 支持 反对

使用道具 举报

发表于 2009-8-17 14:30:23 | 显示全部楼层
Post by jiazhen20;2017002
没人知道么 详解一下 这个无法控制么 想得到例子中的结果该如何呢?

1,加入同步机制
2,运行n次,直到出现书中的结果
回复 支持 反对

使用道具 举报

发表于 2009-8-24 17:47:29 | 显示全部楼层
什么锁呀,互斥量阿,能用的全都给他用上。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-9-4 11:27:09 | 显示全部楼层
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t locker=PTHREAD_MUTEX_INITIALIZER;


void thread(void)
{
int i;
for(i=0;i<3;i++)
{
pthread_mutex_lock(&locker);

printf("This is a pthread.\n");

pthread_mutex_unlock(&locker);

sleep(1);
}
}

int main(void)
{
pthread_t id;
int i,ret;

ret=pthread_create(&id,NULL,(void *) thread,NULL);

for(i=0;i<3;i++)
{
pthread_mutex_lock(&locker);

printf("This is the main process.\n");

pthread_mutex_unlock(&locker);
sleep(1);
}
return (0);
}


改动一下后,结果成功,但不是很爽的。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2009-9-4 11:27:51 | 显示全部楼层
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t locker=PTHREAD_MUTEX_INITIALIZER;


void thread(void)
{
int i;
for(i=0;i<3;i++)
{
pthread_mutex_lock(&locker);

printf("This is a pthread.\n");

pthread_mutex_unlock(&locker);

sleep(1);
}
}

int main(void)
{
pthread_t id;
int i,ret;

ret=pthread_create(&id,NULL,(void *) thread,NULL);

for(i=0;i<3;i++)
{
pthread_mutex_lock(&locker);

printf("This is the main process.\n");

pthread_mutex_unlock(&locker);
sleep(1);
}
return (0);
}

改成这样 成功 不爽
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表