wait()可以代替sleep()或delay()吗?

标签 c multithreading

我的程序中有两个单独的线程,我想让一个线程(比如 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/

相关文章:

c - 当你可以直接将指针传递给 C 中的函数时,为什么还要使用 memcpy() 呢?

C - int 和 malloc

java - 如果可以使用 synchronized(this),为什么还要使用 ReentrantLock?

java - 多线程中的套接字 "deadlocked"Java

C# - 同步 HttpWebRequest 以便从服务器获得响应

java - 在测试中杀死一个java线程

c - 用于通过 wifi radio 向其范围内的设备发送广播数据包的套接字程序

c - 维基百科关于重入的错误吗?

c - 是否有可能在 c 中有一个数组 union

c# - FileStream 锁定文件以进行读写