我的程序中有两个单独的线程,我想让一个线程(比如 Thread1 )延迟 5 秒,以便另一个线程(比如 Thread2)可以完成。但它们不会互相 fork ,两者都是单独的子线程线程。我知道我可以使用delay()或sleep(),但是我可以在Thread1内使用wait(5000)来延迟它5秒吗?或者 Wait() 只能由父线程调用?
最佳答案
等待
来自wait手册:
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);
All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal.
因此,wait
接受一个指向整数的指针 (int(*)
),但它用于获取子级的返回状态。执行 wait(5000)
不会等待 5 秒。正如 @alk 所说在评论中,这样做很可能会让你的程序崩溃。
sleep
sleep
等待给定的秒,但是如果您的 Thread1
被中断的时间超过该时间(非常不太可能,但谁知道呢...),你的 sleep
将变得毫无用处。
pthread_join
要等待线程完成,您可以使用 pthread_join 。从它的手册:
int pthread_join(pthread_t thread, void **retval);
The pthread_join() function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join() returns immediately. The thread specified by thread must be joinable.
使用 pthread
系列函数时,请记住使用 -pthread 进行编译和链接。
您的问题是:wait()可以代替sleep()或delay()吗?
答案:不。。
关于wait()可以代替sleep()或delay()吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32885122/