我希望執行緒中的while回圈運行,等待一秒鐘,然后再次運行,依此類推。但這似乎不起作用,我該如何解決?
main(){
bool flag = true;
pthread = CreateThread(NULL, 0, ThreadFun, this, 0, &ThreadIP);
}
ThreadFun(){
while(flag == true)
WaitForSingleObject(pthread,1000);
}
uj5u.com熱心網友回復:
這是一種方法,我更喜歡使用條件變數而不是睡眠,因為它們回應更快,并且 std::async 優于 std::thread (主要是因為 std::async 回傳一個可以將資訊發送回起始執行緒的未來。即使此示例中未使用該功能)。
#include <iostream>
#include <chrono>
#include <future>
#include <condition_variable>
// A very useful primitive to communicate between threads is the condition_variable
// despite its name it isn't a variable perse. It is more of an interthread signal
// saying, hey wake up thread something may have changed that's interesting to you.
// They come with some conditions of their own
// - always use with a lock
// - never wait without a predicate
// (https://www.modernescpp.com/index.php/c-core-guidelines-be-aware-of-the-traps-of-condition-variables)
// - have some state to observe (in this case just a bool)
//
// Since these three things go together I usually pack them in a class
// in this case signal_t which will be used to let thread signal each other
class signal_t
{
public:
// wait for boolean to become true, or until a certain time period has passed
// then return the value of the boolean.
bool wait_for(const std::chrono::steady_clock::duration& duration)
{
std::unique_lock<std::mutex> lock{ m_mtx };
m_cv.wait_for(lock, duration, [&] { return m_signal; });
return m_signal;
}
// wiat until the boolean becomes true, wait infinitely long if needed
void wait()
{
std::unique_lock<std::mutex> lock{ m_mtx };
m_cv.wait(lock, [&] {return m_signal; });
}
// set the signal
void set()
{
std::unique_lock<std::mutex> lock{ m_mtx };
m_signal = true;
m_cv.notify_all();
}
private:
bool m_signal { false };
std::mutex m_mtx;
std::condition_variable m_cv;
};
int main()
{
// create two signals to let mainthread and loopthread communicate
signal_t started; // indicates that loop has really started
signal_t stop; // lets mainthread communicate a stop signal to the loop thread.
// in this example I use a lambda to implement the loop
auto future = std::async(std::launch::async, [&]
{
// signal this thread has been scheduled and has started.
started.set();
do
{
std::cout << ".";
// the stop_wait_for will either wait 500 ms and return false
// or stop immediately when stop signal is set and then return true
// the wait with condition variables is much more responsive
// then implementing a loop with sleep (which will only
// check stop condition every 500ms)
} while (!stop.wait_for(std::chrono::milliseconds(500)));
});
// wait for loop to have started
started.wait();
// give the thread some time to run
std::this_thread::sleep_for(std::chrono::seconds(3));
// then signal the loop to stop
stop.set();
// synchronize with thread stop
future.get();
return 0;
}
uj5u.com熱心網友回復:
雖然另一個答案是一種可能的方法,但我的答案主要是從不同的角度回答,試圖看看你的代碼可能有什么問題......
flag好吧,如果您不想在設定為時等待一秒鐘,false并且您希望延遲至少 1000 毫秒,那么回圈Sleep可以作業,但您需要
- 一個原子變數(例如
std::atomic) - 或函式(例如
InterlockedCompareExchange) - 或一個
MemoryBarrier - 或其他一些同步方式來檢查標志。
如果沒有適當的同步,就不能保證編譯器會從記憶體而不是快取或暫存器中讀取值。
從 UI 執行緒中使用Sleep或類似的功能也將是可疑的。
對于控制臺應用程式,如果您的應用程式的目的確實是在給定的持續時間內作業,您可以在主執行緒中等待一段時間。但通常,您可能希望等到處理完成。在大多數情況下,您通常應該等待已啟動的執行緒已經完成。
函式的另一個問題Sleep是,即使無事可做,執行緒也總是必須每隔幾秒喚醒一次。如果您想優化電池使用,這可能會很糟糕。但是,另一方面,如果您的代碼中有一些錯誤,則等待某個信號(句柄)的函式具有相對較長的超時時間可能會使您的代碼更健壯地防止錯過喚醒。
在某些情況下,您還需要延遲,因為您實際上沒有任何等待,但您需要定期提取一些資料。
大超時也可以用作一種看門狗計時器。例如,如果您希望有事可做并且在很長一段時間內什么都沒有收到,您??可以以某種方式報告警告,以便用戶可以檢查某些事情是否無法正常作業。
我強烈建議您在撰寫多執行緒代碼之前閱讀一本關于多執行緒的書,例如Concurrency in Action 。
如果沒有正確理解多執行緒,幾乎 100% 肯定任何代碼都會被竊聽。您需要正確理解 C 記憶體模型 ( https://en.cppreference.com/w/cpp/language/memory_model ) 才能撰寫正確的代碼。
等待自己的執行緒沒有意義。當您等待一個執行緒時,您正在等待它已經終止,顯然如果它已經終止,那么它就不能執行您的代碼。您的主執行緒應該等待后臺執行緒終止。
我通常還建議在 API 上使用 C 執行緒函式,因為它們:
- 使您的代碼可移植到其他系統。
- 通常是比相應的 Win32 API 代碼更高級別的構造 (
std::async,std::future,std::condition_variable...)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/412304.html
標籤:
