gpt4 book ai didi

c - C 中的 POSIX 线程

转载 作者:行者123 更新时间:2023-12-04 06:02:57 25 4
gpt4 key购买 nike

我正在尝试了解线程的工作原理。我有一些学校的例子。在这一篇中,我必须弄清楚为什么这段代码不能正常工作。它的输出是这样的:

Main: Creating thread 0
Main: Creating thread 1
Main: Creating thread 2
Main: Creating thread 3
Main: Creating thread 4
Main: Creating thread 5
Main: Creating thread 6
Main: Creating thread 7
Main: Creating thread 8
Thread 0: English: Hello World!
Thread 0: English: Hello World!
Thread 0: English: Hello World!
Thread 0: English: Hello World!
Thread 0: English: Hello World!
Thread 0: English: Hello World!
Thread 0: English: Hello World!
Thread 0: English: Hello World!
Thread 0: English: Hello World!

但是每个线程都应该用不同的语言说“Hello World”。这是我的代码。当函数 pthread_create 中的第四个参数只是 (void *) t 而不是指针时,它工作正常。但我知道正确的解决方案是使用 (void *) &t。可能我正在处理一些指针问题,但我看不到路......

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

#define NUM_THREADS 8

char *messages[NUM_THREADS + 1] =
{
"English: Hello World!",
"French: Bonjour, le monde!",
"Spanish: Hola al mundo",
"Klingon: Nuq neH!",
"German: Guten Tag, Welt!",
"Russian: Zdravstvytye, mir!",
"Japan: Sekai e konnichiwa!",
"Latin: Orbis, te saluto!",
"Cesky: Ahoj svete!"
};


void * helloThread ( void * threadid )
{
int *id_ptr, taskid;

sleep(1);
id_ptr = (int *) threadid;
taskid = *id_ptr;
printf("Thread %d: %s\n", taskid, messages[taskid]);
return(NULL);
}

int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc, t;

for(t=0;t<=NUM_THREADS;t++) {
printf("Main: Creating thread %d\n", t);
rc = pthread_create(&threads[t], NULL, helloThread, (void *) &t );
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
return (EXIT_FAILURE);
}
}

pthread_exit(NULL);
return ( 0 );
}

最佳答案

有几处错误:

首先,你越界了;循环应该说 for(t = 0; t < NUM_THREADS; t++) .

其次,你必须在结束进程之前加入或分离线程,所以在最后说:

for(t = 0; t < NUM_THREADS; ++t) {
pthread_join(threads[t], NULL);
}

第三,您将相同的指针(即 &t )传递给所有线程。这不仅会给您带来错误的行为,而且还会由于竞争条件或取消引用悬挂指针而使您暴露于未定义的行为。相反,给每个线程自己的内存:

int q[NUM_THREADS];  /* dedicated storage for each thread! */

for(t = 0; t < NUM_THREADS; ++t) {
printf("Main: Creating thread %d\n", t);
q[t] = t;
rc = pthread_create(threads + t, NULL, helloThread, q + t);
/* ... */
}

(第四,你不应该像终止主线程那样调用pthread_exit。这是不必要的,它会阻止你以通常的方式从main()返回。)

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

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