这个简单的pthread代码的奇怪行为

nik*_*nik 4 c++ pthreads

如果我将编译并运行下面的代码

  1 #include <iostream>
  2 #include <pthread.h>
  3 #include <cstdio>
  4 #include <cstdlib>
  5
  6 #define NTHREADS 4
  7 #define N 100
  8 #define MEGEXTRA 1000000
  9
 10 using namespace std;
 11
 12 pthread_attr_t attr;
 13
 14 void *doWork (void *threadid) {
 15     double A[N][N];
 16     int tid = *(reinterpret_cast<int *>(threadid));
 17     size_t myStackSize;
 18     pthread_attr_getstacksize (&attr, &myStackSize);
 19     cout << "Thread " << tid << ": stack size = " << myStackSize << " bytes" << endl;
 20
 21     for (int i = 0; i < N; i++) {
 22         for (int j = 0; j < N; j++) {
 23             A[i][j] = ((i * j) / 3.452) + (N - 1);
 24         }
 25     }
 26
 27     pthread_exit (NULL);
 28 }
 29
 30 int main () {
 31     pthread_t threads[NTHREADS];
 32     size_t stackSize;
 33
 34     pthread_attr_init (&attr);
 35     pthread_attr_getstacksize (&attr, &stackSize);
 36
 37     cout << "Default stack size = " << static_cast<long>(stackSize) << endl;
 38
 39     stackSize = sizeof(double) * N * N + MEGEXTRA;
 40     cout << "Amount of stack needed per thread = " << static_cast<long>(stackSize) << endl;
 41
 42     pthread_attr_setstacksize (&attr, stackSize);
 43     cout << "Creating threads with stack size = " << static_cast<long>(stackSize) << endl;
 44
 45     int i[NTHREADS];
 46     for (int j = 0; j < NTHREADS; j++) {
 47         sleep(1);
 48         i[j] = j;
 49
 50         int rc = pthread_create(&threads[j], &attr, doWork, reinterpret_cast<void *>(&i[j]));
 51         if (rc) {
 52            cout << "Error Code: " << rc << endl;
 53             exit (-1);
 54         }
 55     }
 56
 57     cout << "Created " << NTHREADS << " threads" << endl;
 58     pthread_exit(NULL);
 59 }
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

Default stack size = 8388608
Amount of stack needed per thread = 1080000
Creating threads with stack size = 1080000
Thread 0: stack size = 1080000 bytes
Thread 1: stack size = 1080000 bytes
Thread 2: stack size = 1080000 bytes
Created 4 threads
Thread 3: stack size = 1080000 bytes
Run Code Online (Sandbox Code Playgroud)

但如果我要评论睡眠(1); 在第47行,我得到以下输出

Default stack size = 8388608
Amount of stack needed per thread = 1080000
Creating threads with stack size = 1080000
Created 4 threads
Thread 3: stack size = 1080000 bytes
Thread 2: stack size = 1080000 bytes
Thread 1: stack size = 1080000 bytes
Thread 9251904: stack size = 1080000 bytes /** ERROR should be Thread 0: stack size = 1080000 /**
Run Code Online (Sandbox Code Playgroud)

谁能解释一下发生了什么?为什么睡眠(1)注释掉时输出错误?

这就是我用来编译代码的东西

g++ -Wall -Wextra -O2 -ggdb -pthread 5.cpp -o 5
Run Code Online (Sandbox Code Playgroud)

Rap*_*rre 5

那是因为在所有创建的线程都有时间运行之前,主线程(创建其他线程的线程)退出(通过 - 的反转pthread_exit- 并且你终于得到了结束main).i在所有线程读取数组时,数组被破坏并包含垃圾.

你必须等待 - 即pthread_join- 你的子线程在main可以退出之前.

sleep你花了一些时间让线程执行,但仍然由操作系统决定谁在什么时候运行.它可能发生sleep(1)在足够,或者不够,或者没有人在邮递员来到并交付之前运行.

打电话pthread_join,你会安全的.