【发布时间】: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(&tid01, NULL, PrintOut01(), NULL);编译了吗? -
您必须启用编译警告,您的
PrintOut0n()函数返回void *并且您没有从它们返回任何内容,但是您的代码已编译并且您没有提及任何警告。 -
始终检查所有相关系统调用的结果!
-
另外,
pthread_mutex_t lock在所示代码中未初始化使用。如果您检查了对pthread_mutex*()函数的调用结果,您会被告知。 -
谢谢,现在我知道问题所在了。
标签: c multithreading pthreads