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

Function running in a different thread produces weird outputs

本文关键字:输出 函数 线程 运行      更新时间:2023-10-16

你好,我是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

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

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

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

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消息:这是消息

我建议你多读一些关于线程概念的书。它背后的概念并不简单,从长远来看,仅仅准备一个现成的解决方案对你没有帮助。