cout 不能一致地打印字符串和变量值,导致输出未对齐
cout not printing string and variable value consistently , misaligning the output
在下面的代码中,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::mutex
和 std::lock_guard
,因为它们可以保证正确的清理(请参阅其他答案(。由于您的代码中pthread_exit()
,我假设您仅限于 POSIX 线程模型。
相关文章:
- 使用变量值作为 PlaySound 中的路径
- 通过指针偏移量访问结构变量值
- 变量值在 C++ 中的 glutIdleFunc() 中未递增
- 更新 #ifdef 中的现有变量值?
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- 通过 Rcpp 和 bit64 R 包将最大的int64_t变量值从 C++ 传递到 R
- 如何使用 IRBuilder 更新 LLVM IR 中的全局变量值?
- 更改已在运行的程序的变量值
- 在 Xcode 中使用后对外部变量值进行初始化
- C++整数变量值
- 变量值,在三元运算符之后
- 如何获得对不同类的引用,以便从所述类内部获得变量值
- Java应用程序的JNI-c++变量值
- 如何固定从传感器获得的变量值
- 离开方法时重置变量值
- 打印具有通用特定变量值的类对象
- 在宏函数C++中设置宏变量值
- 为什么每次迭代都会获得相同的变量值? C++
- 我使用箭头运算符打印出对象的变量值,并得到一些随机值作为输出
- cout 不能一致地打印字符串和变量值,导致输出未对齐