使用Pthread(主)C打印结果

时间:2013-01-31 15:38:24

标签: c pthreads

我正在尝试在C中创建一个简单的程序,它将使用主线程来打印结果,但是当我创建线程时检查线程ID并且当我打印结果时它有2个不同的ID。这是我的代码: CX

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <sys/time.h>

void *Utskrift(void *simpleInt)
{
  int simple;

simple = (int)simpleInt;
/*Printing my result and thread id*/
printf(";Hello From Thread ! I got fed with
an int %d! AND it is THREAD    ::%d\n",simple,pthread_self());

 }


 main(){

pthread_t thread_id;
int test=2;
/*Using main thread to print test from method Utskrift*/
pthread_create (&thread_id, NULL,&Utskrift,(void *) test);
/*Taking look at my thread id*/
printf(" (pthread id %d) has started\n", pthread_self());
pthread_join(thread_id,NULL);


}

我也是线程编程和C的新手。所以我可能误解了pthread_create (&thread_id, NULL,&Utskrift,(void *) test);。它是否使用我的主线程调用方法Utskrift并打印结果,或者它是否为我的主线程创建了一个新线程“子”,然后子项打印结果?如果是这样,你能否告诉我如何使用主线程来打印我的“测试”。

输出:

(pthread id -1215916352) has started ;Hello From Thread ! I got fed with an int 2! AND it is THREAD ::-1215919248

3 个答案:

答案 0 :(得分:1)

main()也是一个主题。因此,当您创建一个线程时,您基本上从main()派生并在新线程中处理其他内容。 pthread_join()将等待新线程退出,然后继续主线程。希望这是有道理的。

答案 1 :(得分:0)

main中的这一行:

printf(" (pthread id %d) has started\n", pthread_self());

正在打印主线程的pthread id,而不是您之前创建的那个。你在线程中得到的id应该与thread_id中存储的id相同。你可能想写:

printf(" (pthread id %d) has started\n", thread_id);

旁注:pthread_t通常大于int。我建议像这样打印:

printf("... %lu ...", ..., (unsigned long)thread_id, ...);

答案 2 :(得分:0)

pthread_create函数(spec)创建一个新线程,它将执行您传递给它的函数(在本例中为Utskrift)。在pthread_create的最后一个参数中传递的值值将传递给函数。

如果您只是想在主线程中调用Utskrift函数,可以按照正常方式执行:

Utskrift((void *)test));

如果要将数据从已完成的线程传递回另一个线程,可以使用pthread_join,它将返回线程的启动例程返回的值,或者线程传递给{{1}的值}:

pthread_exit