【问题标题】:My threads are not parallel, they are serial. How to make them parallel?我的线程不是并行的,它们是串行的。如何使它们平行?
【发布时间】:2015-09-15 02:45:13
【问题描述】:

我正在练习多线程。

我创建了两个向屏幕显示文本的 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_ */

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;

}

myfunc.h

#ifndef HDR_MYFUNC_H_
#define HDR_MYFUNC_H_
#include "../hdr/hdr.h"
void * PrintOut01 (void);
void * PrintOut02 (void);
#endif /* HDR_MYFUNC_H_ */

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);
    }
}

【问题讨论】:

  • pthread_create(&amp;tid01, NULL, PrintOut01(), NULL); 编译了吗?
  • 您必须启用编译警告,您的 PrintOut0n() 函数返回 void * 并且您没有从它们返回任何内容,但是您的代码已编译并且您没有提及任何警告。
  • 始终检查所有相关系统调用的结果!
  • 另外,pthread_mutex_t lock 在所示代码中未初始化使用。如果您检查了对 pthread_mutex*() 函数的调用结果,您会被告知。
  • 谢谢,现在我知道问题所在了。

标签: c multithreading pthreads


【解决方案1】:

这是因为你在 调用pthread_create 调用中的函数,你没有传递函数指针。

比较不正确

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

正确的

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

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

【讨论】:

  • 即使在将函数指针正确传递给pthread_create() 之后,有问题的特定函数具有错误的签名。每个都应该接受一个void * 类型的参数。如果他们不这样做,那么 UB 将从 pthread_create() 产生,导致他们被调用,就好像他们确实接受了一个参数一样。
猜你喜欢
  • 1970-01-01
  • 2015-04-11
  • 1970-01-01
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多