簡體   English   中英

如何在程序啟動時啟動C ++線程?

[英]How do I start a C++ thread at program startup?

我正在編寫一個C ++庫,允許程序與雲中的服務進行通信。 我想運行一個后台線程,它定期檢查服務器並在發生故障時重新啟動它。 然而,對於庫外的主程序而言,不必擔心啟動線程會很好。 庫的使用應限於useProcess() 到目前為止,線程應該已經在運行。

如果主程序不必調用任何函數,如何啟動一個線程? 有沒有辦法在我的服務類的靜態構造函數中執行此操作,以便它在程序啟動時啟動線程(就像我在Java中一樣)?

你可以這樣做 - 你可以有一個全局對象,其構造函數在程序啟動時啟動線程。

就個人而言,我認為讓一個庫意外啟動一個線程不是一個好主意,但它可能在你的用例中有意義。 確保記錄線程的精確要求,如何關閉它,等等。 流程中的所有線程都必須合作。

示例代碼:

#include <cstdio>

//--------- BEGIN LIBRARY
class MyThread
{ // The real code goes here
public:
    MyThread()
    { printf("A MyThread has been constructed\n"); }
    ~MyThread()
    { printf("A MyThread has been destroyed\n"); }
    void Start()
    { printf("A MyThread has been started\n"); }
    void Stop()
    { printf("A MyThread has been stopped\n"); }
};

class MyThreadCreator
{ // Just a helper class to construct/start/stop/destroy the other
public:
    MyThread thread;
    MyThreadCreator() { thread.Start(); }
    ~MyThreadCreator() { thread.Stop(); }
};
MyThreadCreator p;
//---------- END LIBRARY

int main()
{
    printf("Main\n");
    return 0;
}

MyThread已經構建完成
MyThread已經開始了
主要
MyThread已被停止
MyThread已被破壞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM