简体   繁体   English

线程父子打印文本C语言

[英]Thread parent and son to print a text C language

I've wrote a program in which I create a thread in main that has a son who calls maFunction to show a text message . 我写了一个程序,我在main中创建了一个有一个调用maFunction来显示文本消息的儿子的线程。 The problem is that when I execute this it doesn't work and I don't understand why . 问题是,当我执行它时,它不起作用,我不明白为什么。 Any idea is welcomed . 欢迎任何想法。 Thank you very much . 非常感谢你 。

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
void * maFonction (void * val) {
    char * chaine = (char *) val;
    printf ("text received: %s\n", chaine);
}

int main(void) {
    pthread_t leThread;
    int ret = pthread_create (&leThread, NULL, maFonction, "First program with Pthreads");
    if (ret != 0) {
        perror ("pthread_create");
        exit(EXIT_FAILURE) ;
    }
} 

Your program end execution before your thread start. 您的程序在线程启动之前结束执行。

add pthread_join(leThread, NULL); 添加pthread_join(leThread, NULL); at the end of main() main()的末尾

or add sleep(1); 或者加sleep(1); and don't forget to include <unistd.h> for sleep() 并且不要忘记包含<unistd.h> for sleep()

The issue is that your main function is immediately returning. 问题是你的main功能是立即返回。 When it returns, the C standard library then causes a process exit. 当它返回时,C标准库然后导致进程退出。 The process exit kills both the main thread and any other threads. 进程退出会杀死主线程和任何其他线程。 Hence, your sub-thread never gets a chance to start before the main thread has effectively killed it. 因此,在主线程有效地杀死它之前,你的子线程永远不会有机会启动。

Add a sleep(1) just before the closing brace in main to delay the process exit a bit and you'll see your sub-thread's printf fire. main的右大括号之前添加一个sleep(1)来延迟进程退出一点,你会看到你的子线程的printf fire。

+1 to @Nick-s' answer: one ought to pthread_join in order to reap the sub-thread. +1来自@ Nick-s的回答:一个应该pthread_join才能获得子线程。 However, leaving my answer here for its explanation. 但是,请留下我的答案以供其解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM