gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:39:24 24 4
gpt4 key购买 nike

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

  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 }

我得到以下输出:

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

但是如果我注释掉 sleep(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 /**

谁能解释一下这是怎么回事?为什么 sleep(1) 被注释掉后我会得到不正确的输出?

这是我用来编译的代码

g++ -Wall -Wextra -O2 -ggdb -pthread 5.cpp -o 5

最佳答案

那是因为创建其他线程的主线程退出了(通过 pthread_exit 的优点 - 无论如何你都在 main 的末尾)在所有创建的线程有时间运行之前。 i 数组在所有线程读取时被销毁并包含垃圾。

您必须等待 - 即 pthread_join - 在 main 退出之前为您的子线程。

sleep 为线程的执行争取了一些时间,但仍由操作系统决定谁在何时运行。 sleep(1) 可能足够,也可能不够,或者在 postman 来投递之前没有人运行。

调用pthread_join,你就安全了。

关于c++ - 这个简单的 pthread 代码的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7083963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com