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

时间:2015-11-27 09:18:51

标签: c pthreads posix

这应该创建两个线程并让它们宣布它们的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;
}

1 个答案:

答案 0 :(得分:1)

除了评论中提到的未定义行为之外,您还可以将代码重写为而不是使用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_tlong的注释不起作用。没有标准格式说明符可以便携地打印它。如果您真的关心它,请将其转换为unsinged char*并打印字节。

相关问题