【发布时间】:2014-08-04 11:46:08
【问题描述】:
我是线程新手。
我已经编写了一个示例程序来创建一个线程。
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
#include<pthread.h>
void * func(void * temp)
{
printf("inside function\n");
return NULL;
}
int main()
{
pthread_t pt1;
printf("creating thread\n");
pthread_create(&pt1,NULL,&func,NULL);
printf("inside main created thread\n");
return 0;
}
编译后发现答案是:
creating thread
inside main created thread
inside function
inside function
我知道答案可能会有所不同,因为 return 0; 可能会在执行 func 中的 printf 之前被调用。
但是怎么解决的,inside function被打印了两次呢?
关于使用gcc -o temp thread1.c -lpthread 编译
第一次运行:
creating thread
inside main created thread
第二次运行:
creating thread
inside main created thread
inside function
inside function
关于使用gcc -pthread -o temp thread1.c 编译
第一次运行:
creating thread
inside main created thread
inside function
inside function
我在
上观察到了这种行为gcc version: 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
Kernel release:2.6.32-24-generic
glib version:2.11.1
【问题讨论】:
-
您应该始终加入(或分离)您创建的线程。 (但是您看到的行为有点奇怪。您是如何编译的?)
-
当我用
$ gcc test.c -lpthread编译它时,我根本没有得到“内部函数”输出。如果我使用pthread_join,“内部函数”会按预期打印一次。 -
奇怪!它必须与在工作线程中写入 io 缓冲区有关,但随后由主线程刷新,然后才能在工作线程中清除。换句话说,您正在使用的
printf的实现不是线程安全的(这可能不是新闻,我不知道)。但实际的解决方案就是像 Mat 所说的那样使用 join 或 create。 -
我已经看到了这种效果(在 Linux x86_64 机器上)。正如您所说,在 printf() 输出当前行之后,子进程似乎突然(和意外)停止,但在它更新其缓冲区状态之前。但是,我不认为这意味着线程安全问题......我认为这与实现突然线程终止的位置有关——这可能(有可能)在它完成真正的 I/O 之后立即发生(对底层 fd),处于低于 FILE 缓冲区处理的级别。
-
对于任何感兴趣的人,here is a tale 某人通过标准库的旅程试图确定对标准输出的写入实际发生的位置。这是一个关于复杂代码神秘宏定义的悲惨故事。
标签: c multithreading pthreads