0

我一直在尝试使用 pthreads 实现一个餐饮哲学家解决方案,我尝试在我的 Lenovo yoga2pro pc 上运行它(在 windows 8.1 上运行)即使我通过 mingw 安装管理器安装了 windows 的 pthreads 我得到这个错误:它只如果代码的某些部分中有 sleep() 方法,则会发生。

C:\Users\Anil\Desktop\Github>gcc dphi.c -pthread
C:\Users\Anil\AppData\Local\Temp\ccAxhsF4.o:dphi.c:(.text+0x185): undefined refe
rence to `sleep'
C:\Users\Anil\AppData\Local\Temp\ccAxhsF4.o:dphi.c:(.text+0x1de): undefined refe
rence to `sleep'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\A
nil\AppData\Local\Temp\ccAxhsF4.o: bad reloc address 0x0 in section `.data'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link
 failed: Invalid operation
collect2.exe: error: ld returned 1 exit status

当我尝试编译另一个没有 sleep() 方法的文件时。这就是我得到的:

C:\Users\Anil\Desktop\Github>gcc dp.c -pthread
C:\Users\Anil\Desktop\Github>a.exe
Thread 1 says Hello!
Thread 2 says Hi!

它工作得很好。我刚刚开始编写此代码以了解有关线程的更多信息,因为我正在尝试实现将餐饮哲学家解决方案作为一个项目来解决的方法。我不知道我做错了什么。(我尝试在 Windows 上使用 pthread 执行此操作的原因是因为这是必需的)

4

2 回答 2

1

如果我没记错的话,sleep()是一部分unistd.h,而不是pthread……在linux上:添加

#include <unistd.h>

(并根据需要链接相应的库)

在 Windows 上(您的情况)我不知道等效项,但请检查您是否拥有所有需要的包含(和链接库)

于 2014-05-14T21:05:41.253 回答
1

天真的方法:

#include <windows.h>
// Win32's Sleep() is in millis
#define sleep(n) Sleep(n*1000)
#define usleep(n) Sleep(n/1000)
于 2014-05-14T21:09:36.597 回答