在不同线程中运行的函数会产生奇怪的输出

时间:2016-08-03 04:56:24

标签: c++ multithreading c++11

您好我是C ++中多线程的新手。我正在使用C ++ 11中提供的线程类,以便在不同的线程中运行函数,但不知何故我从函数中获得的输出非常尴尬。这可能是因为不同的线程可能试图同时执行同一个变量,从而导致冲突。请建议我应该如何修改我的代码,以便我能得到正确的输出。我发布了一个我想要做的示例代码。这不是原始代码,但它只显示原始代码的流程,因为我的原始代码太长而无法发布,但问题在两种情况下都是一样的。

    #include<iostream>
    #include<thread>    

    using namespace std;

    typedef struct {
         int thread_id;
         char *message;
    }threadData;

    int display(threadData *tData){
         threadData *my_data;
         my_data = (threadData *) tData;

         cout << "Thread ID: " << my_data -> thread_id << endl; 
         cout << "Message: " << my_data -> message << endl; 

         return 0;
    }

  int main(){

      threadData *data;

      data = (threadData *)malloc(sizeof(threadData));
      data->thread_id = 12;
      data->message = "This is the message"; 
      for (int i = 0; i<10; i++)
      {
          std::thread t1(display, data);    
          t1.detach();
      }
      return 0;
  }

输出:

    Thread ID: 12
    Message: This is the messageThread ID: 
    12
    Message: This is the message
    Thread ID: 12
    Message: This is the message
    Thread ID: 12
    Message: This is the message
    Thread ID: 12
    Message: This is the message

2 个答案:

答案 0 :(得分:2)

我读到的是预期运行10次的for循环,但它只运行了4次,原因是因为在main函数中你没有等待所有的线程完成,所以主进程退出之前其他线程有机会运行。 &#39;主&#39;需要睡一会儿等待所有线程完成他们的工作。

我在这里没有看到竞争条件,因为所有线程只是读取,没有人写入threadData。

答案 1 :(得分:0)

由于线程没有首先运行的保证, 您需要保护对共享资源的访问。 最简单的方法是通过互斥锁。

std::mutex g_i_mutex;  // protects g_i

typedef struct {
     int thread_id;
     string message;
}threadData;

int display(threadData *tData)
{
 std::lock_guard<std::mutex> lock(g_i_mutex);
 threadData *my_data;
 my_data = (threadData *) tData;

 cout << "Thread ID: " << my_data -> thread_id << endl; 
 cout << "Message: " << my_data -> message << endl; 

 return 0;

}

输出:

  

主题ID:12   消息:这是消息   主题ID:12   消息:这是消息   主题ID:12   消息:这是消息   主题ID:12   消息:这是消息

我建议你阅读更多关于线程概念的内容。它背后的概念并不简单,只要获得现成的解决方案,从长远来看对你没有帮助。