2015-01-21 134 views
1

下面是一些代碼,我有atm。你可以選擇線程池中的線程來執行(boost)

int main() 
{ 

    boost::thread_group threads; // Thread Pool 

    // Here we create threads and kick them off by passing 
    // the address of the function to call 
    for (int i = 0; i < num_threads; i++) 
     threads.create_thread(&SendDataToFile); 

    threads.join_all(); 

    system("PAUSE"); 

} 

void SendDataToFile() 
{ 
    // The lock guard will make sure only one thread (client) 
    // will access this application at once 
    boost::lock_guard<boost::mutex> lock(io_mutex); 
    for (int i = 0; i < 5; i++) 
     cout << "Writing" << boost::this_thread::get_id() << endl; 
} 

此刻我只是使用cout而不是寫入文件。

是否有可能在另一個線程之前實際選擇一個線程來執行操作。所以我有一個我想要寫入的文件,4個線程想要同時訪問該文件,是否有可能讓我先說第2個線程。 ? in BOOST

fstream可以像cout一樣使用嗎?當我寫入文件的輸出不是混亂的(沒有互斥)?但是當我打印到沒有互斥體的控制檯時,就像你期望的那樣很麻煩。

+0

鏈接可能會有所幫助http://en.wikipedia.org/wiki/Scheduling_%28computing%29 – user2202911 2015-01-21 10:27:16

+0

@ user2202911有沒有關於此的任何提升示例? – CodersSC 2015-01-21 10:42:07

+0

我不知道任何 - 對不起。 – user2202911 2015-01-21 10:47:43

回答

0

有很多等價的方法可以使用受原子更新,互斥鎖,信號量,條件變量等保護的全局變量的組合來完成此操作。我認爲最直接的方式就是傳達您的想法試圖做的是讓你的線程在ticket lock上等待,而不是他們的票號代表他們到達鎖的順序,它被選擇爲線程被創建的順序。您可以將該想法與Boost spinlock example結合起來,以獲得簡單且可能高性能的實現。