cout 不能一致地打印字符串和变量值,导致输出未对齐

cout not printing string and variable value consistently , misaligning the output

本文关键字:输出 变量值 对齐 字符串 不能 打印 cout      更新时间:2023-10-16

在下面的代码中,threadCount是 1,2,3,4 之一。但是在输出中,虽然字符串部分被完美打印,但 num 值会随机丢失,有时会在几行后附加。

void *SPWork(void *t)
{
    int* threadC = (int*)t;
    int threadCount = *threadC;
    cout<<"n Thread count" << threadCount << endl;
    cout << flush;
    long long int i, adjustedIterationCount;
    adjustedIterationCount = 100/(threadCount);
    for (i=0; i< adjustedIterationCount; i++)
    {
        i++ ;
    }
    pthread_exit((void*) t);
}

输出

......
.....
Thread count1
 Thread count1
 Thread count2
 Thread count1
 Thread count
 Thread count
 Thread count234
 .....
 .....

请注意,最后一行中的线程值为 234。但是该值永远不会 234.In 前 2 行,该值没有附加,因此 2,3 被添加到此行。

我知道这与刷新或附加""有关,尝试了许多组合。但是,问题仍然存在。

:注:这是一个 pthread 的工作方法,编译器标志"-g -Wall -O3 -lpthread"

虽然标准流保证是线程安全的,但不能保证输出不会交错。 如果要以可预测的方式从多个线程打印到标准流,则需要自己执行一些同步:

std::mutex cout_mutex;
void *SPWork(void *t)
{
    //...
    {
        std::lock_guard<std::mutex> guard(cout_mutex);
        std::cout << "n Thread count" << threadCount << std::endl;
    }
    //...
}

要求对cout的调用是原子操作。如果需要它们,只需使用互斥锁保护代码(仅输出代码(。

此外,将std::endl注入流已经刷新了数据,因此在std::flush之后几乎没有意义。

因此,以最简单的形式:

pthread_mutex_lock(&myMutex);
std::cout << "n Thread count" << threadCount << std::endl;
pthread_mutex_unlock(&myMutex);

请注意,对于最近的C++实现,最好使用 std::mutexstd::lock_guard,因为它们可以保证正确的清理(请参阅其他答案(。由于您的代码中pthread_exit(),我假设您仅限于 POSIX 线程模型。