gpt4 book ai didi

在 C 中创建多个线程 : write pid, tid 并返回整数

转载 作者:太空宇宙 更新时间:2023-11-04 04:36:57 27 4
gpt4 key购买 nike

我必须这样做:

编写一个程序,其主线程创建 3 个其他线程。这些线程(不同于主线程)中的每一个都应写入其 pid 和 tid,并终止返回 1 到 3 之间的整数,并且不同于其他线程返回的值。主线程应在标准输出中打印其 pid 和每个其他线程返回的值。

我认为我做对了,除了我不明白我应该如何返回 1 到 3 之间的整数

到目前为止,我有以下代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#define DEBUG 0

// int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);

// int pthread_join(pthread_t, void **value_ptr);

void *printID(void *arg){

int i;

unsigned long tid;
tid = *((unsigned long *) arg);

printf("Thread tid: %lu Thread pid: %d \n", tid, getpid());

}

int main(int argc, char *argv[]) {

pthread_t id1, id2, id3;

pthread_create(&id1, NULL, printID, &id1);

pthread_create(&id2, NULL, printID, &id2);

pthread_create(&id3, NULL, printID, &id3);

pthread_join(id1, NULL);

pthread_join(id2, NULL);

pthread_join(id3, NULL);

printf("Main thread pid: %d\n", getpid());

sleep(1);

}

最佳答案

因为 c 中的线程可以返回 void*。您可以为要返回的 int 分配一个空间,从 main 中读取它,但不要忘记释放它。

关于在 C 中创建多个线程 : write pid, tid 并返回整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858939/

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