繁体   English   中英

c++多线程程序输出不一致

[英]Inconsistent output from c++ multithreaded program

我在 C++ 中有以下程序:

// multithreading01.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <process.h>

using namespace std;

bool threadFinished = false;

struct params {

    string aFile;
    bool tf;

};

void WriteToFile(void *p)
{
    params* a = (params*)p;
    cout<<a->aFile<<endl;
    a->tf = true;
    _endthread();
}

int main(int argc, char* argv[])
{
    params *param01 = new params;
    params *param02 = new params;

    param01->aFile = "hello from p1";
    param01->tf = false;
    param02->aFile = "hello from p2";
    param02->tf = false;

    _beginthread(WriteToFile,0,(void *) param01);
    _beginthread(WriteToFile,0,(void *) param02);

    while(!param01->tf || !param02->tf)
    {

    }
    cout << "Main ends" << endl;
    system("pause");
    return 0;
}

但是,我得到了不一致的输出,例如

输出 1:

来自 p1 的你好 来自 p2 的你好

输出 2:

你好来自 p1 你好来自 p2

输出 3:

你好来自 p2ello 来自 p1

如何从此代码获得一致的输出? 我使用的是 Visual C++ 6.0 标准版。

阅读这篇小文章

就像评论中提到的每个人一样,当您创建线程时,一般来说,想法是分离任务,从而提高现代多核架构 CPU 的性能,每个内核可以有一个线程。

如果你想从两个不同的线程访问相同的资源(在你的情况下是同一个文件),那么你需要确保不会发生来自两个线程的同时访问,否则你会看到你看到的问题。

您通过使用一些锁(例如POSIX 锁或您可以选择特定于平台的锁实现)保护共享资源来提供安全的同时访问。

初学者常犯的错误是他们锁定了“代码”而不是“资源”。

不要这样做:

void WriteToFile(void *p)
{
    pthread_mutex_lock(var); //for example only
    params* a = (params*)p;
    cout<<a->aFile<<endl;
    a->tf = true;
    _endthread();
    pthread_mutex_unlock(var); //for example only
}

您应该改为锁定您的资源

struct params {
    lock_t lock; //for example only not actual code
    string aFile;
    bool tf;    
};

void WriteToFile(void *p)
{
    params* a = (params*)p;
    pthread_mutex_lock(a->lock); //Locking params here not the whole code.
    cout<<a->aFile<<endl;
    a->tf = true;
    pthread_mutex_unlock(a->lock); //Unlocking params
    _endthread();
}

暂无
暂无

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

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