c-C线程创建在20行程序中.为什么不起作用?

c-C线程创建在20行程序中.为什么不起作用?,第1张

概述我试图运行一个简短的程序,在一个for循环中创建三个线程,每个线程都将“内部”写入屏幕. Cygwin在XP和Vista上运行在不同的机器上.这是当前的代码. #include <iostream>#include <unistd.h>#include <pthread.h>#include <semaphore.h>using namespace std;void* printInsi 我试图运行一个简短的程序,在一个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.

输出通常由标准库缓冲.它在某些情况下被刷新,但有时您必须手动执行.所以即使线程运行并产生输出,除非你刷新它,你将看不到它.

总结

以上是内存溢出为你收集整理的c-C线程创建在20行程序中.为什么不起作用?全部内容,希望文章能够帮你解决c-C线程创建在20行程序中.为什么不起作用?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1253689.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存