我一直在尝试使用pthreads实现一个餐饮哲学家解决方案,我尝试在我的联想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上使用pthreads这样做是因为它是一个要求)
答案 0 :(得分:1)
如果我没错,sleep()
是unistd.h
的一部分,而不是pthread
...
在 linux :添加
#include <unistd.h>
(并根据需要链接相应的库)
在Windows上(你的情况)我不知道相同的,但检查你有所有需要的包括(和链接的库)
答案 1 :(得分:1)
天真的方法:
#include <windows.h>
// Win32's Sleep() is in millis
#define sleep(n) Sleep(n*1000)
#define usleep(n) Sleep(n/1000)