加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:11:52 所属栏目:百科 来源:网络整理
导读:我试图运行一个简短的程序,在一个for循环中创建三个线程,每个线程都将“内部”写入屏幕. Cygwin在XP和Vista上运行在不同的机器上.这是当前的代码. #include iostream#include unistd.h#include pthread.h#include semaphore.husing namespace std;void* prin
我试图运行一个简短的程序,在一个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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读