簡體   English   中英

C ++打印/裁剪在多線程中重疊嗎?

[英]C++ Printing/cout overlaps in multithreading?

我想知道使用多個線程時如何處理打印。
我認為這將非常簡單:

#include <iostream>
#include <pthread.h>
using namespace std;

bool printing = false;

struct argumentStruct {
    int a;
    float b;
};

void *ThreadFunction(void *arguments) {
  struct argumentStruct*args = (struct argumentStruct*)arguments;
  int a = args->a;
  float b = args->b;
    while (printing) {}
    printing = true;
      cout << "Some text...." << a << b << endl;
    printing = false;
}

main() {
    pthread_t threads[3];
    struct argumentStruct argStruct[3];

    argStruct[0].a = 1;
    argStruct[0].b = 1.1;
    pthread_create(&threads[0], NULL, &ThreadFunction, (void *)&argStruct[0]);

    argStruct[1].a = 2;
    argStruct[1].b = 2.2;
    pthread_create(&threads[1], NULL, &ThreadFunction, (void *)&argStruct[1]);

    argStruct[2]a = 3;
    argStruct[2].b = 3.3;
    pthread_create(&threads[2], NULL, &ThreadFunction, (void *)&argStruct[2]);

    getchar();
    return 0;
}

但這並不能很好地工作。 一些提示只是被跳過(或可能被覆蓋?)。
那我在做什么錯? 我該如何正確處理?

問題在於測試和設置printing變量的語句不是原子的 ,也就是說,它們不會在不被線程間切換CPU的OS調度程序中斷的情況下執行。 您應該使用互斥鎖以便在打印時停止其他線程。 這里有一個很好的例子:

http://sourcecookbook.com/en/recipes/70/basic-and-easy-pthread-mutex-lock-example-c-thread-synchronization

你有一個競爭條件,其中兩個(或更多)線程都可以設置printingtrue

這是因為賦值不是原子操作,它是由CPU分多個步驟完成的,並且如果在將變量的實際設置為true之前中斷了該線程,並且另一個線程開始運行,那么您可以讓兩個線程同時運行相信變量是true 為了更清楚:

  1. 線程A看到printing false
  2. 線程A被中斷
  3. 線程B開始運行
  4. 線程B看到printing false
  5. 線程B將printing設置為true
  6. 線程B被中斷
  7. 線程A已排定並再次開始運行
  8. 線程A將printing設置為true

現在,線程A和B都在全速運行。

這就是為什么有線程基元(例如, 信號量互斥 量)來處理這些事情的原因。

暫無
暫無

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

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