使用 Pthread(主)C 打印结果



我正在尝试用 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    ::%dn",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 startedn", 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()将等到新线程退出,然后继续使用主线程。希望这是有道理的。

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

如果您只想在主线程中调用 Utskrift 函数,则可以按正常方式进行操作:

Utskrift((void *)test));

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

#include <pthread.h>
#include <stdio.h>
void *checker(void *arg) {
    int number = (int) arg;
    if (0 == number)
        return "number was zero";
    else
        return "number was not zero";
}
int main(void) {
    int test = 0;
    pthread_t thread_id;
    char *s;
    pthread_create (&thread_id, NULL, checker,(void *) test);
    pthread_join(thread_id, &s);
    printf("%sn", s);
    test = 1;
    pthread_create (&thread_id, NULL, checker,(void *) test);
    pthread_join(thread_id, &s);
    printf("%sn", s);
    return 0;
}

main中的这一行:

printf(" (pthread id %d) has startedn", pthread_self());

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

printf(" (pthread id %d) has startedn", thread_id);

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

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

最新更新