我想在C中使用主线程来打印结果,但当我创建线程时检查线程ID,当我打印结果其2不同标识。这里是我的代码: CX打印结果与Pthread(主)C
#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
您可以发布您的输出? – noMAD
(pthread id -1215916352)已经开始 ; Hello From Thread!我吃了一个int 2!它是线程:: - 1215919248 –
请在这里发布时请正确格式化您的代码。另外你的'(void *)测试'东西是残酷的。在你理解的状态下,你绝对不应该使用演员,而后来当你更坚定地使用演员时,尽可能少。如果你从某个地方复制了这样的东西,也许改变你的来源。 –