gpt4 book ai didi

c - 是否可以在多个文件中创建线程并在主文件中执行?

转载 作者:行者123 更新时间:2023-11-30 18:46:32 25 4
gpt4 key购买 nike

我有以下结构想要与 2 个独立线程上的排序器(无限循环)和网络器(无限循环)进行交互。线程在各自的文件中生成,而不是在主文件中生成。这有什么问题吗?

main.c

int main(void {
network();
sorter();
}

sort.c//创建随机数组,然后在连续的 while 循环中对它们进行排序(永不结束)

void sorter() {
int r1 = pthread_create(&thread1, NULL, (void *) &sorter, NULL);
pthread_join(thread1, NULL);
}

int* getArray() { ... }
int getElement() { ... }

网络.c

void network() {
int r2 = pthread_create(&thread2, NULL, (void *) &startNetwork, NULL);
pthread_join(thread2, NULL);
}

void startNetwork() {
int sockfd, portno, optval, n;
socklen_t adSize;
struct sockaddr_in servAd, clientAd;
...
while(1) {
//receive packet
int *arr = getArray();
// send packets
// or receive packet that has a command to get array
}

}

是否可以有这样的线程结构?我的主文件会因为未在主文件中创建线程而卡住吗?有更好的方法吗?

最佳答案

sorter() 的主要问题是 (1) 在线程函数返回之前它不会返回,以及 (2) 线程函数是 sorter(),所以你有一个无限循环。这可能是尝试将代码抽象到问题中时出现的问题。有一些具体细节需要修复,例如函数的类型等。

network() 的问题可能相似或不同;您还没有显示从 main() 调用的函数,因此不清楚您的意图。 networker() 中的代码不好;它使 pthread_create() 调用具有错误签名的函数 - 线程函数应具有签名 void *function(void *arg);

不过,一般来说,在不同源文件的代码中启动不同的线程是没有问题的。如果线程未分离(如果您要加入它们),那么您需要使由 pthread_create() 初始化的 pthread_t 可用于管理线程的代码连接 - 可能是因为它们位于全局变量或全局数组的一部分中,或者可能是因为您提供了对存储在单独源文件中的私有(private)数据的功能访问。

所以,你可能有:

network.c

static pthread_t thread2;

static void *network_thread(void *arg);

void network(void)
{
if (pthread_create(&thread2, NULL, network_thread, NULL) != 0)
…handle error…
}

void network_join(void)
{
void *vp = 0;
if (pthread_join(&thread2, &vp) != 0)
…report error…
…maybe use the return value in vp…
}

sorter.c

static pthread_t thread1;
static void *sorter_thread(void *arg);

void sorter(void)
{
if (pthread_create(&thread1, NULL, sorter_thread, NULL) != 0)
…handle error…
}

void sorter_join(void)
{
void *vp = 0;
if (pthread_join(&thread1, &vp) != 0)
…handle error…
…maybe use value in vp…
}

main.c

#include "sorter.h"
#include "network.h"

int main(void)
{
network();
sorter();
network_join();
sorter_join();
return 0;
}

您可能会在 network_join()sorter_join() 中构建检查,这样如果您尚未调用 network()sorter(),代码不会尝试加入无效线程。

关于c - 是否可以在多个文件中创建线程并在主文件中执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50780434/

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