Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用pthread并发推送()到共享队列?_C++_Multithreading_Pthreads - Fatal编程技术网

C++ 使用pthread并发推送()到共享队列?

C++ 使用pthread并发推送()到共享队列?,c++,multithreading,pthreads,C++,Multithreading,Pthreads,我正在练习pthread 在我的原始程序中,它将一个名为request的类的实例推送到共享队列中,但我首先要确保我正在将某个对象推送到共享队列中 这是一个非常简单的代码,但它只是抛出了很多错误,我无法找出原因 我想这可能是语法上的问题,但不管我怎么做,都没有用 你明白为什么它不起作用了吗 下面是我一直在尝试的代码 extern "C" { #include<pthread.h> #include<unistd.h> } #include<queue&

我正在练习pthread

在我的原始程序中,它将
一个名为
request
的类的实例推送到共享队列中,但我首先要确保我正在将某个对象推送到共享队列中

这是一个非常简单的代码,但它只是抛出了很多错误,我无法找出原因


我想这可能是语法上的问题,但不管我怎么做,都没有用

你明白为什么它不起作用了吗

下面是我一直在尝试的代码

extern "C" {
    #include<pthread.h>
    #include<unistd.h>
}
#include<queue>
#include<iostream>
#include<string>

using namespace std;

class request {
 public:
    string req;
    request(string s) : req(s) {}

};

int n;
queue<request> q;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

void * putToQueue(string);

int main ( void ) {
    pthread_t t1, t2;

    request* ff = new request("First");
    request* trd = new request("Third");

    int result1 = pthread_create(&t1, NULL, &putToQueue, reinterpret_cast<void*>(&ff));
    if (result1 != 0) cout << "error 1" << endl;
    int result2 = pthread_create(&t2, NULL, &putToQueue, reinterpret_cast<void*>(&trd));
    if (result2 != 0) cout << "error 2" << endl;

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    for(int i=0; i<q.size(); ++i) {
        cout << q.front().req << " is in queue" << endl;
        q.pop();
        --n;
    }

    return 0;
}

void * putToQueue(void* elem) {
    pthread_mutex_lock(&mut);

    q.push(reinterpret_cast<request>(elem));
    ++n;

    cout << n << " items are in the queue." << endl;

    pthread_mutex_unlock(&mut);
    return 0;
}
extern“C”{
#包括
#包括
}
#包括
#包括
#包括
使用名称空间std;
类请求{
公众:
字符串请求;
请求(字符串s):请求{}
};
int n;
队列q;
pthread\u mutex\u t mut=pthread\u mutex\u初始值设定项;
void*putToQueue(字符串);
内部主(空){
pthread_t t1,t2;
请求*ff=新请求(“第一次”);
请求*trd=新请求(“第三次”);
int result1=pthread_create(&t1,NULL,&putToQueue,reinterpret_cast(&ff));

如果(result1!=0)不能下面的代码会对所有必须更改的内容进行注释。我会详细描述它们为什么必须更改,但我希望代码能说明问题。它仍然不是防弹的。有很多事情可以做得不同或更好(失败的
的异常处理,等等)但至少它可以编译、运行并且不会泄漏内存

#include <queue>
#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
using namespace std;

// MINOR: param should be a const-ref
class request {
public:
    string req;
    request(const string& s) : req(s) {}
};

int n;
queue<request> q;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;


// FIXED: made protoype a proper pthread-proc signature
void * putToQueue(void*);

int main ( void )
{
    pthread_t t1, t2;

    // FIXED: made thread param the actual dynamic allocation address
    int result1 = pthread_create(&t1, NULL, &putToQueue, new request("First"));
    if (result1 != 0) cout << "error 1" << endl;

    // FIXED: made thread param the actual dynamic allocation address
    int result2 = pthread_create(&t2, NULL, &putToQueue, new request("Third"));
    if (result2 != 0) cout << "error 2" << endl;

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    // FIXED: was skipping elements because the queue size was shrinking
    //  with each pop in the while-body.
    while (!q.empty())
    {
        cout << q.front().req << " WAS in queue" << endl;
        q.pop();
    }

    return 0;
}

// FIXED: pretty much a near-total-rewrite
void* putToQueue(void* elem)
{
    request *req = static_cast<request*>(elem);
    if (pthread_mutex_lock(&mut) == 0)
    {
        q.push(*req);
        cout << ++n << " items are in the queue." << endl;
        pthread_mutex_unlock(&mut);
    }
    delete req; // FIXED: squelched memory leak
    return 0;
}

如评论中所述,我建议跳过直接使用pthreads,改用C++11线程原语。我从一个简单的受保护队列类开始:

template <class T, template<class, class> class Container=std::deque>
class p_q {
    typedef typename Container<T, std::allocator<T>> container;
    typedef typename container::iterator iterator;

    container data;
    std::mutex m;
public:
    void push(T a) {
        std::lock_guard<std::mutex> l(m);
        data.emplace_back(a);
    }
    iterator begin() { return data.begin(); }
    iterator end() { return data.end(); }
    // omitting front() and pop() for now, because they're not used in this code
};
模板
p_q类{
typedef typename容器;
TypeDefTypeName容器::迭代器迭代器;
集装箱数据;
std::互斥m;
公众:
无效推力(TA){
标准:锁紧装置l(m);
数据。向后放置(a);
}
迭代器begin(){返回数据。begin();}
迭代器end(){return data.end();}
//暂时省略front()和pop(),因为在这段代码中没有使用它们
};
使用此方法,代码的主流几乎与单线程代码一样简单和干净,如下所示:

int main() {
    p_q<std::string> q;

    auto pusher = [&q](std::string const& a) { q.push(a); };

    std::thread t1{ pusher, "First" };
    std::thread t2{ pusher, "Second" };

    t1.join();
    t2.join();

    for (auto s : q)
        std::cout << s << "\n";
}
intmain(){
p_q;
自动推送器=[&q](std::string const&a){q.push(a);};
螺纹t1{pusher,“第一”};
螺纹t2{pusher,“第二”};
t1.join();
t2.连接();
用于(自动s:q)

cout“我想可能是语法问题”你知道什么是语法错误吗?你是不是开始写一个把字符串放在队列中的单线程程序?看起来你几乎不知道C++是什么,并且已经想跳过多线程编程。抱歉,这不是真的。我是一个不错的C++程序员,但是关于pthink我知道的不多。我不相信一个象样的C++。程序员会写
string*msg1=“First”
“我正在练习pthread。”这就是你的错误。几乎可以肯定,你应该使用C++11中包含的线程原语。大多数想法类似,但总体上更干净、更可移植。对不起,代码与我的原始代码相比发生了很大变化,因为我尝试了我能想到的一切,它类似于const char*msg1=(一些字符串)。C_str()@user241822不客气。我希望它能起到一点作用。说真的,先学习pthreads,然后看看And。它们非常优秀,可以让这样的东西变得轻而易举。
int main() {
    p_q<std::string> q;

    auto pusher = [&q](std::string const& a) { q.push(a); };

    std::thread t1{ pusher, "First" };
    std::thread t2{ pusher, "Second" };

    t1.join();
    t2.join();

    for (auto s : q)
        std::cout << s << "\n";
}