多线程中打印问题?

新手上路,请多包涵
#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

运行的结果如下:

阅读 2.9k
2 个回答
我就想弄明白,为什么"This is a thread test\n"会被打印两次。

被打印多少次都不要奇怪, 你在循环创建进程, 进程又创建线程, 很显然, 这两次打印属于两个进程.

#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");
    pthread_join(tid, NULL);  // 等待新线程完成
    return 0;
} 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题