【问题标题】:Why isn't the program waiting for the pthread为什么程序不等待 pthread
【发布时间】:2020-11-05 09:22:08
【问题描述】:

程序没有执行函数 1 的整个 for 循环。 我认为加入线程会使程序等待线程结束。

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void* func1(void* arg) {
    for(int i=0;i<10;i++) {
        printf("Func 1: %d\n", i);
        sleep(1);
    }
    return NULL;
}

void func2(void) {
    for(int i=0;i<5;i++) {
        printf("Func 2: %d\n", i);
        sleep(1);
    }
}

int main(void) {
    pthread_t new_thread;
    pthread_create(&new_thread, NULL, func1, NULL);
    func2();
    pthread_join(&new_thread, NULL);
    return 0;
}

【问题讨论】:

  • 如果您尝试使用 -Wall 进行编译并修复这些错误会发生什么?
  • 阅读您的编译器警告。他们随时为您提供帮助。
  • 欢迎来到 Stack Overflow。请注意,在这里说“谢谢”的首选方式是投票赞成好的问题和有用的答案(一旦你有足够的声誉这样做),并接受对你提出的任何问题最有帮助的答案(这也给出了你的声誉小幅提升)。请查看About 页面以及How do I ask questions here?What do I do when someone answers my question?

标签: c linux pthreads


【解决方案1】:

来自pthread_join

   int pthread_join(pthread_t thread, void **retval);

如您所见,第一个参数是 pthread_t 但您传递的是 pthread_t* - 这就是问题所在。所以你应该使用:

pthread_join(new_thread, NULL);

请注意,如果您对pthread_* 函数调用进行错误检查,您就会发现问题所在。例如,运行您的代码:

errno = pthread_join(&new_thread, NULL);
if (errno) perror("pthread_join");

看看它说了什么。

同样,启用编译器警告(例如 -Wall -Wextra)也会有所帮助。

【讨论】:

  • 感谢您的详细回复,对我帮助很大!
【解决方案2】:

以下建议代码:

  1. 干净编译
  2. 执行所需的功能
  3. 请注意使用适当的水平和垂直间距以提高我们人类的可读性
  4. 请注意退出线程的首选方法。

现在,建议的代码:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>


void* func1( void* arg ) 
{
    (void)arg;  // to avoid compiler warning about unused parameter
    
    for( int i=0; i<10; i++ ) 
    {
        printf( "Func 1: %d\n", i );
        sleep(1);
    }
    pthread_exit( NULL );
}


void func2( void ) 
{
    for( int i=0; i<5; i++ ) 
    {
        printf( "Func 2: %d\n", i );
        sleep(1);
    }
}


int main( void ) 
{
    pthread_t new_thread;
    pthread_create( &new_thread, NULL, func1, NULL );
    func2();
    pthread_join( new_thread, NULL );
    return 0;
}

建议代码的典型运行会导致:

Func 2: 0
Func 1: 0
Func 2: 1
Func 1: 1
Func 2: 2
Func 1: 2
Func 2: 3
Func 1: 3
Func 2: 4
Func 1: 4
Func 1: 5
Func 1: 6
Func 1: 7
Func 1: 8
Func 1: 9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多