从 pthread c++ 丢失打印



我开始使用 pthread of C++,并对多线程(3)进行了简单的检查。但我看到的是,我总是从两条线上得到打印。为什么?

#include <iostream>
#include <string>
#include <pthread.h>
using namespace std;
int N=10;
void* run(void* arg) {  
  char* msg = (char*)arg;
  for(int i; i<=N; ++i) std::cout<<msg<<std::endl;
}
int main(int argc, char* argv[]) {
  if (argc > 1) N = stoi(argv[1]);
  pthread_t t1,t2,t3;
  pthread_create(&t1,NULL,run,(void*)"xxx");
  pthread_create(&t2,NULL,run,(void*)"    howdy");
  pthread_create(&t3,NULL,run,(void*)"          wrold");
  pthread_join(t1,NULL);
  pthread_join(t2,NULL);
  pthread_join(t3,NULL);
  return 0;
}

打印如:

howdy
      wrold
howdy
      wrold
这是

未定义的行为,任何事情都可能发生。

例如,在我的机器上,它根本不打印任何东西。

  • i未初始化。
  • void* run必须返回一些东西(例如:return NULL;

最新更新