gpt4 book ai didi

c - 这是一个过于复杂的 pthreads 代码吗?

转载 作者:行者123 更新时间:2023-11-30 15:14:42 24 4
gpt4 key购买 nike

这应该创建两个线程并让它们宣布它们的 ID 和它们分配的 PID。还实现了一些基本的错误检查。

是否有一种更简单的方法可以在不牺牲错误检查的情况下执行此操作?

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


pthread_t tid[1];

void* doSomething(void *arg)
{
int i = 0;
pthread_t id = pthread_self();
const char* a[2];
a[0]="Client(1)";
a[1]="Server(2)";


while (i<2)
{

if ( pthread_equal(id,tid[i]) )
printf("\n I'm the %s! My ID is: %ld. Our PID is= %d\n",a[i], (long int)&(tid[i]) , getpid());
i++;


}
pthread_exit(0);
}

int main(void)
{
int i = 0;
int error;

while(i < 2)
{
error = pthread_create(&(tid[i]), NULL, &doSomething, NULL);
if (error != 0){
printf("\n Error creating thread %d:[%s]",i+1, strerror(error));
}
else{
if(i==0){
printf("\n Principal thread: Client thread (%i) created! Thread ID: %ld \n", i+1, (long int)&(tid[0]));
}
if(i==1){
printf("\n Principal thread: Server thread (%i) created! Thread ID: %ldn", i+1, (long int)&(tid[1]));
}

i++;
}
}
if ( pthread_join((tid[0]), NULL) == 0){
printf ("\n Client has closed \n");
} else {
printf ("\n Client closed with an error \n");
}
if ( pthread_join((tid[1]), NULL) == 0){
printf ("\n Server has closed \n");
}else{
printf ("\nClient closed with an error \n");
}

return 0;
}

最佳答案

除了注释中提到的未定义行为之外,您还可以重写代码以使用while循环并简化线程函数如:

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

pthread_t tid[2];

void* doSomething(void *arg)
{
char *str = arg;
printf("\n I'm the %s! My ID is: %ld. Our PID is= %d\n", str, (long) pthread_self() , getpid());
pthread_exit(0);
}

int main(void)
{
int i = 0;
int error;
const char *a[2] = {"Client (1)", "Client (2)" };

for(i=0; i<2; i++)
{
error = pthread_create(&(tid[i]), NULL, &doSomething, (void*)a[i]);
if (error != 0)
printf("\n Error creating thread %d:[%s]",i+1, strerror(error));
else
printf("\n Principal thread: Client thread (%i) created! Thread ID: %ld \n", i+1, (long int)&(tid[i]));
}

if ( pthread_join((tid[0]), NULL) == 0){
printf ("\n Client has closed \n");
} else {
printf ("\n Client closed with an error \n");
}
if ( pthread_join((tid[1]), NULL) == 0){
printf ("\n Server has closed \n");
}else{
printf ("\nClient closed with an error \n");
}

return 0;
}

您还可以跳过 pthread_join() 上的错误检查。如果无论如何都失败了,你也无能为力。

此外,请注意将 pthread_t 转换为 long 并不保证有效。没有标准格式说明符可移植地打印它。如果您确实关心它,请将其转换为 unsinged char* 并打印字节。

关于c - 这是一个过于复杂的 pthreads 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954002/

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