1

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

3 回答 3

1

The main() is also a thread. So when you create a thread you basically fork from main() and process something else in the new thread. pthread_join() will wait till you new thread exits and then will continue with the main thread. Hope that makes some sense.

于 2013-01-31T15:48:12.440 回答
0

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

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

Utskrift((void *)test));

如果要将数据从已完成的线程传递回另一个线程,则可以使用pthread_joinwhich 将返回线程启动例程返回的值或线程传递给的值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("%s\n", s);

    test = 1;

    pthread_create (&thread_id, NULL, checker,(void *) test);
    pthread_join(thread_id, &s);
    printf("%s\n", s);

    return 0;
}
于 2013-01-31T16:05:16.327 回答
0

这一行在main

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

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

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

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

printf("... %lu ...", ..., (unsigned long)thread_id, ...);
于 2013-01-31T15:51:12.087 回答