简体   繁体   English

pthread_create无法正确执行

[英]pthread_create does not execute properly

I am learning about multi-thread programs and am expecting the following snippet of code to be an infinite loop of printing " foo" instead nothing happens 我正在学习多线程程序,并且期望以下代码片段是打印“ foo"的无限循环,但没有任何反应

Expectations : 期望 :

foofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoo foofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoo

Reality : 现实情况:

It is as though the thread is not even being created , what am i doing wrong ??? 好像没有创建线程,我在做什么错? How do i create a thread which will execute whatever function is assigned to it 我如何创建一个线程,它将执行分配给它的任何功能

Source code 源代码

#include <pthread.h>
#include <stdlib.h>

#include <stdio.h>

#include <string.h>
#include <iostream>

void* print(void*);

struct threadInfo
{

    int threadID;
    int threadNo;

};

int main()
{
    pthread_t thread[3];
    bool cont = false;
    int i = 1;
    int max = 3;

    while ( cont == false )
    {
        if ( i <= max )
        {
            threadInfo t_info;
            t_info.threadID = i ;
            t_info.threadNo = i ;
            pthread_create(&thread[i-1],NULL,print,(void*)&t_info);

            i++;
        }
    }   





}

void* print(void* arg)
{
  std::cout << "Foo" ; 
  pthread_exit(NULL);
}

The following piece of code is compiled on Ubuntu command line with the following command 以下代码段是使用以下命令在Ubuntu命令行上编译的

g++ test.cpp -o test -lpthread

The threads are created, but before they could run, the main thread exits, and your program terminates (it's also UB). 线程已创建,但是在它们可以运行之前,主线程退出,程序终止(它也是UB)。 You have to wait for your threads: pthread_join 您必须等待线程: pthread_join

The while ( cont == false ) is not needed. 不需要while ( cont == false )

There nothing printed because the output buffers are not flushed . 没有打印任何内容,因为未清除输出缓冲区。

In the print function, do eg print功能中,例如

std::cout << "Foo" << std::flush;

My oh my... Where to start ? 我的天哪...从哪里开始?

The reason why you don't see a thing has been given by Joachim Pileborg: the threads are created all right and do their job, but since your main program never exits and nobody ever outputs a line feed, the line-buffered output is never flushed. 乔阿希姆·皮勒博格(Joachim Pileborg)给出了您看不到任何东西的原因:线程可以正常创建并完成其工作,但是由于您的主程序永不退出,并且没有人输出换行符,因此从不缓冲行输出酡。

Your main program is wasting CPU looping on a flag that will never be changed. 您的主程序在CPU循环上浪费了一个永远不会改变的标志。 Trying to synchronize threads with flags is extremely bad, despite the stupid new C++11 extensions that make atomic variables the alpha and omega of thread programming. 尽管新的C ++ 11愚蠢的扩展使原子变量成为线程编程的alpha和omega,但尝试使线程与标志同步非常糟糕。
You must use some kind of synchro to wait for thread terminations. 您必须使用某种同步来等待线程终止。 The most usual mechanism is pthread_join . 最常用的机制是pthread_join

Passing the same instance of parameters to each instance of your thread creates a perfect race condition. 将相同的参数实例传递给线程的每个实例可创建理想的竞争条件。 You have no guarantee the thread will read the parameters in your intended order (ie before the main loop changes them to prepare for the next thread launch). 您不能保证线程将按您预期的顺序读取参数(即在主循环更改它们以准备下一次线程启动之前)。 You should pass each thread its own private instance of t_info (or setup some kind of synchronization mechanism over this structure). 您应该为每个线程传递其自己的t_info私有实例(或在此结构上设置某种同步机制)。

Even after fixing all these problems, you should expect only 3 "Foo" since each thread exits after a single print. 即使解决了所有这些问题,您也应该只期望3个“ Foo”,因为每个线程在一次打印后都会退出。

And since you don't serialize the cout accesses (ie you don't protect them with some kind of synchro object like a mutex), it is possible the outputs of your various threads will be mixed at random (ie you could see something like "FoFFooooo"). 而且由于您不对cout访问进行序列化(即,您不使用某种互斥对象(例如互斥锁)保护它们),因此可能会随机混合各个线程的输出(即,您可能会看到类似“FoFFooooo”)。

The main thread probably ends (and tremrinates all other thread with this) before any other thread has printed out anything. 在任何其他线程打印出任何内容之前,主线程可能会结束(并用此字符串将所有其他线程删除)。

To fix this either make the main thread join loopig around ( pthread_join() for all thread-ids created) on all other thread before ending, or end the main thread using pthread_exit() . 要解决此问题,请在结束之前使主线程在所有其他线程上加入loopig(为创建的所有线程ID创建pthread_join() ,或使用pthread_exit()结束主线程。


Also passing the address of the same instance of struct threadInfo the each tread (that is: (void*)&t_info ) most probably is not what you want. 还在每个struct threadInfo (即: (void*)&t_info )传递struct threadInfo同一实例的地址,这很可能不是您想要的。

There is nothing wrong with pthreads. pthreads没有错。 If you want to ensure that sequence in the output, you need to enclose the print out line with a lock and a flush, so that you enforce that, 如果要确保输出中的顺序,则需要用锁和同花括号将打印输出行括起来,以便您强制执行此操作,

1. A thread only finishes once the message has actually been printed out
2. Threads wait for each other so that no two threads write to the output at the same time

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM