我正在尝试用 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