pthread创建不正常

Iza*_*agi 2 c pthreads

我有这段代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

问题是主要内部消息"In main: creating thread"显示但线程内部的消息有时不显示.

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

Alo*_*ave 10

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

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

在pthread_join()

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

for(i=0; i<number; i++)
{
    pthread_join(threads[i], NULL);
}
Run Code Online (Sandbox Code Playgroud)

其他问题:

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