c - 使用 Pthread (main) C 打印结果

标签 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

最佳答案

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

关于c - 使用 Pthread (main) C 打印结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14629437/

相关文章:

c++ - 静态 .lib 文件如何相互链接?

c++ - 用 C++ 线程模拟 pthread_kill

python - python支持哪些模块来生成c代码?

c - 在 c 中将 const char* 转换为 char* 的问题

c - MyThreadYield(void) 中的 getcontext() 获取空上下文

c - sigwait 在 MacOS 上复制和转换信号

c - 这个死锁隐藏在哪里?

c - Larry, Moe, Curly 互斥

c - BullsEye代码覆盖率

c - 缓冲服务器 C