gpt4 book ai didi

c - 代码的执行顺序

转载 作者:行者123 更新时间:2023-12-04 03:34:14 24 4
gpt4 key购买 nike

sample output

谁能解释一下这段代码的执行顺序?

我在尝试理解代码流的工作原理时卡在了 pthread_join 部分:

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 25

int thread_routine (int x)
{
printf ( "I'm Thread %2d my TID is %u\n", x, pthread_self () );
pthread_exit(0);
}

int main ()
{
pthread_attr_t thread_attr;
pthread_t tids[NUM_THREADS];
int x;
pthread_attr_init (&thread_attr);

for (x = 0; x < NUM_THREADS; x++)
{
pthread_create (&tids[x], &thread_attr, (void *)thread_routine, (void *) x);
}

printf ("Waiting for threads to finish\n");

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

printf ("All treads are now finished\n");
}

最佳答案

我看执行顺序没有问题。线程按顺序创建,自行执行,然后您从头到尾加入它们。

经过一些修改,代码在我的机器上运行良好,这是一台运行 Linux (Kubuntu 16.04 x86_64) 的旧 x86 Thinkpad。我用 g++11 编译。

请注意,您需要小心处理 pthread_create 参数以及处理线程函数的输入。 x 是一个整数,作为参数得到的是一个指向 void 的指针,所以要取回 x,需要先将 x:s 地址发送到 pthread_create,然后通过将 void 指针转换为 int 指针和检索 int 指针指向的 int 值。呃……如果你在 pthreads 之上使用薄的 std::thread 包装器会容易得多。

您还可以发送 nullptr 并跳过创建 attr 参数,因为您没有使用任何非默认线程属性。

#include <pthread.h>
#include<stdio.h>
#define NUM_THREADS 25

int thread_routine (void* p)
{
int x = *((int*)p);
printf ( "I'm Thread %2d my TID is %u\n", x, (unsigned int)pthread_self () );
pthread_exit(0);
}

int main () {
pthread_attr_t thread_attr;
pthread_t tids[NUM_THREADS];
int x;
int (*start_routine)(void*) = thread_routine;
pthread_attr_init (&thread_attr);
for (x = 0; x < NUM_THREADS; x++)
{
pthread_create(&tids[x], &thread_attr,
(void* (*)(void*))start_routine,
(void*) &x);
}
printf ("Waiting for threads to finish\n");
for (x = 0; x < NUM_THREADS; x++)
{
pthread_join (tids[x], NULL);
}
printf ("All treads are now finished\n");
}

关于c - 代码的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964101/

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