我试图运行一个简短的程序,在一个for循环中创建三个线程,每个线程都将“内部”写入屏幕. Cygwin在XP和Vista上运行在不同的机器上.这是当前的代码.
#include <iostream> #include <unistd.h> #include <pthread.h> #include <semaphore.h> using namespace std; void* printInside(void* arg); int main() { pthread_t threads[3]; for(int i = 0; i < 3; i++) { pthread_create(&threads[i],printInside,0); } return 0; } void* printInside(void* arg) { cout << "inside"; return 0; }
它不行.如果我在for循环的内部添加一个cout,它似乎放慢了工作.
for(int i = 0; i < 3; i++) { cout << ""; pthread_create(&threads[i],0); }
有什么建议,为什么是这样的情况?
编辑:
在回路之后,我收到了添加一个连接的响应
int main() { pthread_t threads[3]; for(int i = 0; i < 3; i++) { pthread_create(&threads[i],0); } for(int i = 0; i < 3; i++) { void* result; pthread_join(threads[i],&result); } } void* printInside(void* arg) { cout << "inside"; return 0; }
但还是不行,加盟做错了吗?
固定
“Output is usually buffered by the standard library. It is flushed in certain circumstances but sometimes you have to do it manually. So even if the threads run and produce output you won’t see it unless you flush it.”
解决方法
您需要加入或主线程将退出:
for(int i = 0; i < 3; i++) { pthread_create(&threads[i],0); } /* Join here. */
If I add a cout to the inside of the for loop,it appears to slow it
down into working.
执行I / O通常是硬而缓慢的.这给了其他线程足够的cpu时间来运行.
记住,当使用多个线程时,如果一个呼叫退出,它们都会死亡.
编辑
adding an endl to the end of “inside” does make it work better,but it
seems like a cop-out solution. Just wondering why it would be
necessary even with the join present.
输出通常由标准库缓冲.它在某些情况下被刷新,但有时您必须手动执行.所以即使线程运行并产生输出,除非你刷新它,你将看不到它.