gpt4 book ai didi

c - Posix线程问题

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

我试图通过示例来理解 pthreads。我编写了以下代码,每次运行时都会给出不同的答案!谁能解释一下这个错误?TIA,斯维亚

代码在这里:

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

#define NUM_THREADS 4

struct thread_data {
int thread_id;
int sum;
};

struct thread_data thread_data_array[NUM_THREADS];

void *PrintHello(void *threadarg)
{
struct thread_data *my_data;
int taskid;
int sum;

my_data = (struct thread_data *) threadarg;
taskid = my_data->thread_id;
sum = my_data->sum;

printf("Hello World! It's me, thread #%d\n", taskid);

return my_data;
}

int main ()
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
int sum=0;

for (t=0; t < NUM_THREADS; t++) {
printf("Hi! %ld\n", t);

threads[t] = t;

thread_data_array[t].thread_id = t;
thread_data_array[t].sum = sum;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &thread_data_array[t]);
}

return 0;
}

输出在这里:

[user@office tmp]$ ./a.out 
Hi! 0
Hi! 1
Hello World! It's me, thread #0
Hello World! It's me, thread #1
Hi! 2
Hi! 3
Hello World! It's me, thread #2
[user@office tmp]$ ./a.out
Hi! 0
Hi! 1
Hello World! It's me, thread #0
Hello World! It's me, thread #1
Hi! 2
Hi! 3
Hello World! It's me, thread #2
Hello World! It's me, thread #3
[user@office tmp]$ ./a.out
Hi! 0
Hello World! It's me, thread #0
Hi! 1
Hello World! It's me, thread #1
Hi! 2
Hello World! It's me, thread #2
Hi! 3
Hello World! It's me, thread #3
[user@office tmp]$ ./a.out
Hi! 0
Hi! 1
Hello World! It's me, thread #0
Hi! 2
Hi! 3
Hello World! It's me, thread #3
[user@office tmp]$

最佳答案

没有错误,这就是线程的工作方式。您的主线程创建新线程,这些线程此时“准备好运行”。在某个时间点(由操作系统确定),您的主线程将被挂起,其他线程之一将运行一定时间(通常是几十毫秒)。当您的程序存在正在运行的线程时,系统将在线程之间不断切换。

您的主线程将被中断并且其他线程之一可以打印它的确切时间点 Hello World 将取决于操作系统调度程序的决定,基于您的主线程已经运行了多长时间,其他线程中的事件系统、外部(I/O)事件等。

编辑以在下面包含我的评论:

您看到 3 个,然后是 4 个,然后只有 2 个“Hello Worlds”的原因是您创建了线程,但没有等待它们真正被调度和运行。当你的主循环结束时,程序就死了,不管你的其他线程是否有机会运行。如果您希望完成所有线程,则需要在从 main 返回之前对每个线程执行 pthread_join

关于c - Posix线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1680224/

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