jjzjj

c++ - P线程锁定

coder 2024-02-17 原文

我已经创建了这样的 MutexCondition 类

/*MutexCondtion.h file*/
#ifndef MUTEXCONDITION_H_
#define MUTEXCONDITION_H_

#include <pthread.h>
#include <stdio.h>

class MutexCondition {

private:
    bool init();
    bool destroy();

protected:
    pthread_mutex_t m_mut;
    pthread_cond_t m_con;

public:
    MutexCondition(){
        init();
    }
    virtual ~MutexCondition(){
        destroy();
    }

    bool lock();
    bool unLock();
    bool wait();
    bool signal();

};
#endif /* MUTEXCONDITION_H_ */

MutexCondtion.cpp文件

#include "MutexCondition.h"

bool MutexCondition::init(){
    printf("MutexCondition::init called\n");
    pthread_mutex_init(&m_mut, NULL);
    pthread_cond_init(&m_con, NULL);
    return true;
}

bool MutexCondition::destroy(){
    pthread_mutex_destroy(&m_mut);
    pthread_cond_destroy(&m_con);
    return true;
}

bool MutexCondition::lock(){
    pthread_mutex_lock(&m_mut);
    return true;
}

bool MutexCondition::unLock(){
    pthread_mutex_unlock(&m_mut);
    return true;
}

bool MutexCondition::wait(){
    pthread_cond_wait(&m_con, &m_mut);
    return true;
}

bool MutexCondition::signal(){
    pthread_cond_signal(&m_con);
    return true;
}

我创建了一个扩展 MutexCondition 的 WorkHandler

#ifndef WORKHANDLER_H_
#define WORKHANDLER_H_

#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <pthread.h>
#include <stdio.h>
#include <list>

#include "MutexCondition.h"
#include "Work.h"

using namespace::std;

class WorkHandler: MutexCondition {

private:
    int m_maxThreads;

    queue<Work*> m_workQueue;
    list<pthread_t*> m_workThreadList; //Just thread IDs

    pthread_t **m_workThreads;

    void workLoop();
    bool initThreads();
    void insertWork(Work *work);
    Work* getWork();

protected:
    static void* runWorkThread(void* delegate);

public:
    WorkHandler(int maxThreads);
    virtual ~WorkHandler();
};

#endif /* WORKHANDLER_H_ */

WorkHandler.cpp 文件

#include "WorkHandler.h"

WorkHandler::WorkHandler(int maxThreads) {
    // TODO Auto-generated constructor stub
    m_maxThreads = maxThreads;
    initThreads();
}

WorkHandler::~WorkHandler() {
    // TODO Auto-generated destructor stub
}

void* WorkHandler::runWorkThread(void *delegate){
    printf("WorkHandler::runWorkThread called\n");

    WorkHandler *ptr = reinterpret_cast<WorkHandler*>(delegate);
    ptr->workLoop();
    return NULL;
}

void WorkHandler::workLoop(){
    printf("WorkHandler::workLoop called\n");

    //WorkHandler *ptr = reinterpret_cast<WorkHandler*>(delegate);

    while(1){
        Work *work = getWork();
    }
}

bool WorkHandler::initThreads(){

    for(int i=0; i < m_maxThreads; i++){
        pthread_t *thread(new pthread_t);
        m_workThreadList.push_back(thread);

        if(pthread_create(thread, NULL, runWorkThread, reinterpret_cast<void *>(this))!=0){
            perror("InitThreads, pthread_create error \n");
            return false;
        }

        pthread_detach(*thread);
    }

    return true;
}

void WorkHandler::insertWork(Work* w){
    printf("WorkHandler::Thread %d insertWork locking\n", pthread_self());
    lock();
    printf("WorkHandler::insertWork Locked and inserting int queue \n");
    m_workQueue.push(w);
    signal();
    unLock();
}

Work* WorkHandler::getWork(){
    printf("WorkHandler::getWork locking\n");
    lock();
    printf("WorkHandler::getWork locked\n");
    while(m_workQueue.empty()){//Need while instead of If
        printf("WorkHandler::getWork waiting...\n");
        wait();
    }
    Work *work = m_workQueue.front();
    printf("WorkHandler::getWork got a job\n");
    m_workQueue.pop();
    unLock();

    return work;
}

问题是我像这样在 getWork() 函数中锁定了互斥变量

    printf("WorkHandler::getWork locking\n");
    lock();
    printf("WorkHandler::getWork locked\n");

但是,如果我看到日志语句,那么所有线程都打印了这两个日志语句,我认为这是一个问题。我没有将任何东西放入队列中,因此第一个线程应该等待条件变量发出信号并且它工作正常。但是为什么其他线程可以进入锁后面的区域,尽管第一个线程锁定并且没有调用 unlock() 函数。

我想知道这是否正常工作。如果你们能看到我需要修复的任何东西,请告诉我。提前致谢。

最佳答案

原因是当一个线程等待一个条件变量时,互斥锁被解锁。

这是预期的行为。

当条件变量发出信号时,线程不会被释放运行,直到重新获取锁。

如果你把函数改成这样:

Work* WorkHandler::getWork(){
          // Remoed this as it is non-determinstic when it will be printed.
    lock();
    printf("WorkHandler::getWork locked\n");
    while(m_workQueue.empty()){//Need while instead of If
        printf("WorkHandler::getWork waiting...\n");
        wait();
        printf("WorkHandler::getWork waiting DONE\n");    // Added this.
    }
    Work *work = m_workQueue.front();
    printf("WorkHandler::getWork got a job\n");
    m_workQueue.pop();
    unLock();

    return work;
}

如果您随后创建了三个线程,我希望:

WorkHandler::getWork locked
WorkHandler::getWork waiting...
WorkHandler::getWork locked;
WorkHandler::getWork waiting...
WorkHandler::getWork locked
WorkHandler::getWork waiting...

对于我期望的每次信号调用:

WorkHandler::Thread %d insertWork locking
WorkHandler::insertWork Locked and inserting int queue
WorkHandler::getWork waiting DONE
WorkHandler::getWork got a job

无论你调用 signal 的速度有多快,我总是希望看到这两个按顺序打印。
因为线程在重新获取锁之前不会从条件变量中释放。

注意你可能会看到。

WorkHandler::Thread %d insertWork locking
WorkHandler::insertWork Locked and inserting int queue
WorkHandler::getWork locked                              // A previously released thread finishes and steals 
                                                         // the job before the signalled thread can aquire the lock.
WorkHandler::getWork got a job
WorkHandler::getWork waiting DONE                        // Now the released thread just goes back to waiting.
WorkHandler::getWork waiting...

关于c++ - P线程锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6367235/

有关c++ - P线程锁定的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  3. ruby-on-rails - Rails - 乐观锁定总是触发 StaleObjectError 异常 - 2

    我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd

  4. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  5. ruby - 如何让Ruby捕获线程中的语法错误 - 2

    我正在尝试使用ruby​​编写一个双线程客户端,一个线程从套接字读取数据并将其打印出来,另一个线程读取本地数据并将其发送到远程服务器。我发现的问题是Ruby似乎无法捕获线程内的错误,这是一个示例:#!/usr/bin/rubyThread.new{loop{$stdout.puts"hi"abc.putsefsleep1}}loop{sleep1}显然,如果我在线程外键入abc.putsef,代码将永远不会运行,因为Ruby将报告“undefinedvariableabc”。但是,如果它在一个线程内,则没有错误报告。我的问题是,如何让Ruby捕获这样的错误?或者至少,报告线程中的错误?

  6. ruby - 如何在 ruby​​ 中运行后台线程? - 2

    我是ruby​​的新手,我认为重新构建一个我用C#编写的简单聊天程序是个好主意。我正在使用Ruby2.0.0MRI(Matz的Ruby实现)。问题是我想在服务器运行时为简单的服务器命令提供I/O。这是从示例中获取的服务器。我添加了使用gets()获取输入的命令方法。我希望此方法在后台作为线程运行,但该线程正在阻塞另一个线程。require'socket'#Getsocketsfromstdlibserver=TCPServer.open(2000)#Sockettolistenonport2000defcommandsx=1whilex==1exitProgram=gets.chomp

  7. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  8. ruby - Rails 开发服务器、PDFKit 和多线程 - 2

    我有一个使用PDFKit呈现网页的pdf版本的Rails应用程序。我使用Thin作为开发服务器。问题是当我处于开发模式时。当我使用“bundleexecrailss”启动我的服务器并尝试呈现任何PDF时,整个过程会陷入僵局,因为当您呈现PDF时,会向服务器请求一些额外的资源,如图像和css,看起来只有一个线程.如何配置Rails开发服务器以运行多个工作线程?非常感谢。 最佳答案 我找到的最简单的解决方案是unicorn.geminstallunicorn创建一个unicorn.conf:worker_processes3然后使用它:

  9. arrays - Ruby 数组 += vs 推送 - 2

    我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“

  10. += 的 Ruby 方法 - 2

    有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=

随机推荐