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

标签 c++ multithreading

我正在尝试运行一个在 for 循环中创建三个线程的短程序,每个线程都将“内部”写入屏幕。在不同机器上同时运行 XP 和 Vista 的 Cygwin 会发生这种情况。这是当前代码。

#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], 0, 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, printInside, 0);
}

关于为什么会这样有什么建议吗?

编辑:

我收到了在循环后添加连接的回复

int main()
 {
     pthread_t threads[3];
     for(int i = 0; i < 3; i++)
    {
        pthread_create(&threads[i], 0, printInside, 0);
    }
     for(int i = 0; i < 3; i++)
    {
        void* result;
        pthread_join(threads[i],&result);
    }
}
 void* printInside(void* arg)
 {
    cout << "inside";
    return 0;
}

但是还是不行,是不是join做错了?

固定

"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, printInside, 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 时间来运行。

请记住,在使用多个线程时如果一个调用exit,它们都会死掉

编辑

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++ - 在 20 行程序中创建 C 线程。为什么它不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10390616/

相关文章:

java - 为什么主线程等待

java - 为什么使用两个线程作为计数器会降低 Java 的性能?

c++ - 在大项目中使用 c++11 std::tuple

c++ - 静态模板类的建议

python - GTK3+ 和 Python 中的线程同步

java - AtomicReference 的各个元素上的数据争用

java - 应该从事件调度程序还是主线程控制 Swing GUI 应用程序?

c++ - 在调试过程中如何查看 Qt 对象 QByteArray 的内容?

c++ - 模板函数的歧义递归定义

c++ - 函数的默认值作为函数参数