pthread 创建无法正常工作 [英] pthread creation not working properly

查看:46
本文介绍了pthread 创建无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>

int number;
pthread_mutex_t  *mutex;
pthread_t *threads;

void *PrintHello(void *threadid)
{
    long tid;
    tid = (long)threadid;
    printf("Hello World! It's me, thread #%ld!\n", tid);
    time_t rawtime;
    struct tm * time_start;
    time ( &rawtime );
    time_start = localtime ( &rawtime );
    printf ( "The number %ld thread is created at time %s  \n",tid, asctime     (time_start));
    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    int i,rc;

    printf("give threads");
    scanf("%d",&number);
    mutex = calloc( number, sizeof(*mutex));
    threads = calloc(number, sizeof(*threads));

    for (i = 0; i < number;i++) {
        pthread_mutex_init( &mutex[i],NULL);
    }

    for(i=0; i<number; i++){
        printf("In main: creating thread %d\n", i);
        rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
        if (rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    return 0;
}

此代码的目的是要求用户提供将要创建的线程数,创建线程后,线程本身将打印 2 条消息,说明线程数和时间它是创建的.

The purpose of this code is to ask the user to give the number of the threads that it is going to create and after the creation of the threads,the thread itself will print 2 messages saying the number of the thread and the time that it was created.

问题是在 main 中,消息 In main: created thread" 显示出来,但线程中的消息有时不显示.

The problem is that inside the main the message "In main: creating thread" is showing up but the message inside the threads sometimes does not.

例如,它将创建 3 个线程,只有 1 个线程会显示其消息,并且该线程也不会显示创建的时间.不知道是不是代码有问题.

For example, it would create 3 threads and only 1 thread will show up its message and that thread also will not show up the time that was created. I dont know if there is something wrong with the code.

推荐答案

根本原因:
您的 main() 在子线程有机会完成其任务之前退出.

Root Cause:
Your main() exits before the child threads get an opportunity to complete their task.

解决方案:
您需要确保 main() 等待所有线程完成其工作.
您需要使用:

Solution:
You need to make sure that the main() waits until all the threads have completed their work.
You need to use:

pthread_join()

来实现这个功能.在从 main() 返回之前添加以下内容:

to achieve this functionality. Add the following before returning from main():

for(i=0; i<number; i++)
{
    pthread_join(threads[i], NULL);
}

其他问题:

  • 您动态分配内存但从不释放它.尽管如此,一旦您的程序返回,操作系统就会回收内存.明确地这样做是一种很好的做法.
  • 您创建了一个互斥锁,但您既不使用它,也不释放它.但这似乎是正在进行的代码.

这篇关于pthread 创建无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆