用c创建一个pthread,等待创建线程完成执行[关闭]

问题描述 投票:-1回答:1

下面的代码,我创建一个pthread,然后我让主线程等待创建的线程完成执行:

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

void * createThread(void * u){
  printf("Tread has been created");
}

int main(){
  //pthread_t tid;
  //pthread_create(&tid,NULL,&createThread,NULL);
  //printf("Main thread");

  //pthread_join(tid,NULL);

  pthread_t tid[2];
  int i;
  for(i = 0; i < 2; i++){
    pthread_create(&tid[i],NULL,&createThread,NULL);
  }
  int j;
  for(j = 0; j < 2; i++){
    pthread_join(tid[j],NULL);
  }
  return 0;
}

当我通过起诉gcc 1_4.c -lpthread然后./a.out来运行这个我必须等待很长时间才能在终端中看到答案!

我做错了什么,或者我无法看到问题。

c multithreading compilation
1个回答
1
投票

在以下循环中,您将增加i而不是j

   for(j = 0; j < 2; i++){
    pthread_join(tid[j],NULL);
}

将其更改为以下,它将正常工作:

   for(j = 0; j < 2; j++){
    pthread_join(tid[j],NULL);
}
© www.soinside.com 2019 - 2024. All rights reserved.