2016-03-01 100 views
-2

這裏是我的簡單代碼,我想獲得console_task,變量i的值在dialer_task ...沒有使用全局變量。線程間通信

#include <stdio.h> 
#include <sys/types.h> 
#include <signal.h> 
#include <strings.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <thread> 
#include "console.hpp" 

using namespace std; 

void console_task(){ 
    console(); 
} 

void dialer_task(){ 
    int i=0; 
    while (1) { 
     printf("LOOP %d\n",i); 
     i++; 
     sleep(5); 
    } 
} 

int main() 
{ 
    thread t1(console_task); 
    thread t2(dialer_task); 

    t1.join(); 
    t2.join(); 
    return 0; 
} 
+1

這看起來像一個家庭作業,所以第一個問題是:你到目前爲止做了什麼? – dmaij

+0

投票結束的話題>爲什麼這段代碼沒有工作。 – Shark

+0

您應該閱讀網站的幫助部分,以便您更好地瞭解如何提出問題。這個頁面可能是有用的:http://stackoverflow.com/help/on-topic – Rook

回答

4

可能沒有全局變量共享線程之間狀態的限制基本上留下了2個可行的備選方案;

  1. 在堆上分配的共享狀態並傳遞到螺紋
  2. 分配原始線程堆棧上的共享狀態和「飼料」它的工作線程共享使用。

兩種解決方案的結果都是確保訪問得到適當的保護或原子化。

一個簡單的解決方案是使用std::atomic並在線程之間共享引用。

#include <type_traits> 
#include <thread> 
#include <atomic> 
#include <iostream> 

void console_task(std::atomic_int& j) { 
    using namespace std; 

    int i = 0; 
    while (++i < 50) { 
     cout << "task " << j << endl; // uncontrolled access to the console (demo) 
     std::chrono::microseconds delay{50}; 
     this_thread::sleep_for(delay); 
    } 
} 

void dialer_task(std::atomic_int& j){ 
    using namespace std; 
    int i = 0; 
    while (++i < 10) { 
     //cout << "LOOP " << i << endl; // uncontrolled access to the console (demo) 
     std::chrono::microseconds delay{145}; 
     this_thread::sleep_for(delay); 
     j = i; 
    } 
} 

int main() 
{ 
    std::atomic_int i { 0 }; 
    std::thread t1(console_task, std::ref(i)); 
    // a lambda with reference capture could also be used 
    // std::thread t1([&](){console_task(i);}); 
    std::thread t2(dialer_task, std::ref(i)); 

    t1.join(); 
    t2.join(); 
    return 0; 
} 

有一個catch到共享atomic,它需要保持有效的線程的持續時間(因爲它在這裏)。

Demo code

可以考慮基於堆的替代方案;例如使用共享std::mutex連同std::shared_ptr