我的线程不是并行的,它们是串行的.如何使它们平行?

Tri*_*yen 4 c multithreading pthreads

我正在练习多线程.

我创建两个posix线程,向屏幕显示文本(无限循环),但它似乎只是第一个线程运行.我修改程序没有循环,第一个线程打印,以下是第二个线程.似乎我的线程不是并行的,第一个线程必须在线程二开始之前完成.我怎样才能让它们平行?

谢谢,

hdr.h

#ifndef HDR_HDR_H_
#define HDR_HDR_H_
#define HDR_HDR_H_
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#endif /* HDR_HDR_H_ */
Run Code Online (Sandbox Code Playgroud)

multithread01.c

#include "../hdr/myfunc.h"
pthread_mutex_t lock;

int main(int argc, char **argv)
{
    pthread_t tid01;
    pthread_t tid02;
    void * status01;
    void * status02;

    pthread_create(&tid01, NULL, PrintOut01(), NULL);
    pthread_create(&tid02, NULL, PrintOut02(), NULL);

    pthread_join(&tid01, &status01);
    pthread_join(&tid02, &status02);

    return 0;
Run Code Online (Sandbox Code Playgroud)

}

myfunc.h

#ifndef HDR_MYFUNC_H_
#define HDR_MYFUNC_H_
#include "../hdr/hdr.h"
void * PrintOut01 (void);
void * PrintOut02 (void);
#endif /* HDR_MYFUNC_H_ */
Run Code Online (Sandbox Code Playgroud)

myfunc.c

#include "../hdr/hdr.h"

extern pthread_mutex_t lock;

void * PrintOut01 ()
{
    while (1)
    {
        pthread_mutex_lock(&lock);
        printf ("This is thread 01\n");
        pthread_mutex_unlock(&lock);
    }
}

void * PrintOut02 ()
{
    while (1)
    {
        pthread_mutex_lock(&lock);
        printf ("This is thread 02\n");
        pthread_mutex_unlock(&lock);
    }
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 6

这是因为你在调用函数中调用函数pthread_create,而不是传递函数指针.

比较不正确

pthread_create(&tid01, NULL, PrintOut01(), NULL);
Run Code Online (Sandbox Code Playgroud)

用正确的

pthread_create(&tid01, NULL, PrintOut01, NULL);
Run Code Online (Sandbox Code Playgroud)

如果删除函数中的循环,并像在问题中的代码中那样创建线程,那么pthread_create将使用从函数返回的任何内容作为指向线程函数的指针,除非您返回指向函数的指针你将有未定义的行为.

  • 即使在将函数指针正确传递给`pthread_create()`之后,问题*中的特定函数也会有错误的签名*.每个都应该接受一个类型为`void*`的参数.如果它们没有,那么UB将来自`pthread_create()`,导致它们被调用,好像它们确实接受了一个参数. (3认同)