LinuxSir.cn,穿越时空的Linuxsir!

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

linux线程问题

[复制链接]
发表于 2006-3-30 18:30:30 | 显示全部楼层 |阅读模式
在linux下,线程是由轻量级进程实现的,我创建了一个线程,为什么用ps-A和pstree看不到呢,
void *my_function(void *arg)
{

while(1);
}

#include <pthread.h>
int main()
{
pthread_attr_t attr;
pthread_t tid;

/*初始化属性值,均设为默认值*/
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

pthread_create(&tid, &attr, (void *) my_function, NULL);

}
发表于 2006-3-30 21:29:47 | 显示全部楼层
线程是轻量级的进程,但是并不是说他就是进程.进程包含线程,但是操作系统并不知道线程的存在,只有进程自己知道线程的存在.ps就是把系统的进程打印出来.有些实现是访问进程表.
回复 支持 反对

使用道具 举报

发表于 2006-3-31 10:25:02 | 显示全部楼层
看看你的程序,这个线程根本就没跑,因为main已经返回了,程序就退出了。
在main里面加上一行 pthread_join,等那个线程退出。

看我的测试:

  1. #include <stdio.h>
  2. #include <pthread.h>

  3. void* thread_entry(void* arg)
  4. {
  5.     printf("thread_entry: begins, arg=%p\n", arg);
  6.     getchar();
  7.     printf("thread_entry: exits\n");
  8. }

  9. int main(int argc, char** argv)
  10. {
  11.     pthread_t thread_id;

  12.     if (pthread_create(&thread_id, NULL, thread_entry, NULL) < 0)
  13.         exit(1);
  14.     pthread_join(thread_id, NULL);
  15.     return 0;
  16. }

复制代码

保存为test.c

  1. $ gcc test.c -lpthread -o test
复制代码

在另一个终端:

  1. $ ps ax -L |grep test
  2. 8519  8519 pts/5    Sl+    0:00 ./test
  3. 8519  8520 pts/5    Sl+    0:00 ./test
  4. 8522  8522 pts/2    R+     0:00 grep test
复制代码

看,有两个线程在里面呢。
回复 支持 反对

使用道具 举报

发表于 2006-3-31 19:28:10 | 显示全部楼层
又有收获了呀.
回复 支持 反对

使用道具 举报

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

本版积分规则

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