#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *testThread(void *arg){
printf("This is a thread test\n");
return NULL;
}
int main(){
pthread_t tid;
int ret;
ret = pthread_create(&tid,NULL,testThread,NULL);
printf("This is a main thread\n");
return 0;
}
我把这段代码编译为名为a.out的程序,然后又写了一个shell脚本,shell脚本的功能是无限运行程序,然后等2秒后,我停止运行shell脚本,然后我发现在某次运行a.out时,"This is a thread test\n"被运行了两次,我就有一点疑惑,按理来说,如果testThread有机会运行的话,最多只打印一次"This is a thread test\n",结果就只打印了两次,我就想弄明白,为什么"This is a thread test\n"会被打印两次。
shlle脚本的内容如下
!/bin/bash
while((1))
do
echo "-------------------";
./a.out
echo "--------------------";
done
运行的结果如下:
被打印多少次都不要奇怪, 你在循环创建进程, 进程又创建线程, 很显然, 这两次打印属于两个进程.