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

时间:2015-04-24 23:05:11

标签: c multithreading pid

我必须这样做:

编写一个程序,其主线程创建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);

}

1 个答案:

答案 0 :(得分:0)

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

相关问题