简体   繁体   English

PThread 问题

[英]PThread Question

I am trying to make a small thread example.我正在尝试制作一个小线程示例。 I want to have a variable and each thread try to increment it and then stop once it gets to a certain point.我想要一个变量,每个线程都尝试增加它,然后在它到达某个点时停止。 Whenever the variable is locked, I want some sort of message to be printed out like "thread x trying to lock, but cannot" so that I KNOW it's working correctly.每当变量被锁定时,我都希望打印出某种消息,例如“线程 x 试图锁定,但不能”,以便我知道它工作正常。 This is my first day coding threads so feel free to point out anything unnecessary in the code here -这是我第一天的编码线程,所以请随时在此处的代码中指出任何不必要的内容 -

#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

#define NUM_THREADS 2
pthread_t threads[NUM_THREADS];
pthread_mutex_t mutexsum;

int NUMBER = 0;
void* increaseByHundred(void* threadid) {

    if(pthread_mutex_lock(&mutexsum))
        cout<<"\nTHREAD "<<(int)threadid<<" TRYING TO LOCK BUT CANNOT";

    else {
        for(int i=0;i<100;i++) {
            NUMBER++;
            cout<<"\nNUMBER: "<<NUMBER;
        }
        pthread_mutex_unlock(&mutexsum);
        pthread_exit((void*)0);
    }
}


int main(int argc, char** argv) {

    int rc;
    int rc1;
    void* status;

    pthread_attr_t attr;

    pthread_mutex_init(&mutexsum, NULL);
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    rc = pthread_create(&threads[0], &attr, increaseByHundred, (void*)0);
    rc1 = pthread_create(&threads[1], &attr, increaseByHundred, (void*)1);

    pthread_attr_destroy(&attr);

    while(NUMBER < 400)
        pthread_join(threads[0], &status);


    pthread_mutex_destroy(&mutexsum);
    pthread_exit(NULL);

}

I was following a tutorial found here https://computing.llnl.gov/tutorials...reatingThreads and tried to adapt their mutex example to this idea.我正在按照此处找到的教程https://computing.llnl.gov/tutorials...reatingThreads并尝试使他们的互斥锁示例适应这个想法。 The code increments it up to 199 and then stops.代码将其增加到 199,然后停止。 I'm guessing because the threads are only doing their routine once.我猜是因为线程只执行一次例程。 Is there a way make them just do their routine other than when you create them so I could say有没有办法让他们只做他们的日常工作,而不是当你创建它们时,所以我可以说

while something do your routine?而你的例行公事?

I have the pthread_join there just because it was similar to what that tutorial had on theirs.我在那里有 pthread_join 只是因为它与他们的教程相似。 I don't really even get it that clearly though.不过,我什至不是很清楚。 I'm pretty sure that line is the problem...I just don't know how to fix it.我很确定那条线是问题所在……我只是不知道如何解决它。 Any help is appreciated.任何帮助表示赞赏。

Whenever the variable is locked, I want some sort of message to be printed out like "thread x trying to lock, but cannot" so that I KNOW it's working correctly.每当变量被锁定时,我都希望打印出某种消息,例如“线程 x 试图锁定,但不能”,以便我知道它工作正常。

Why do you want that?你为什么要那个? You are just learning about threads.你只是在学习线程。 Learn the basics first.首先学习基础知识。 Don't go diving off the deep end into pthread_mutex_trylock or mutexes configured for error checking.不要 go 从深处潜入pthread_mutex_trylock或为错误检查配置的互斥锁。 You need to learn to walk before you can learn how to run.你需要先学会走路,然后才能学会跑步。

The basics involves a mutex initialized use with default settings and using pthread_mutex_lock to grab the lock.基础知识包括使用默认设置初始化互斥锁并使用pthread_mutex_lock来获取锁。 With the default settings, pthread_mutex_lock will only return non-zero if there are big, big problems.使用默认设置, pthread_mutex_lock只会在出现大问题时返回非零值。 There are only two problems that can occur here: Deadlock, and a bad mutex pointer.这里只会出现两个问题:死锁和错误的互斥指针。 There is no recovery from either;两者都没有恢复; the only real solution is to fix the code.唯一真正的解决方案是修复代码。 About the only thing you can do here is to throw an exception that you don't catch, call exit() or abort(), etc.在这里你唯一能做的就是抛出一个你没有捕获的异常,调用 exit() 或 abort() 等。

That some other thread has locked the mutex is not a big problem.其他一些线程锁定了互斥锁并不是一个大问题。 It is not a problem at all.这根本不是问题。 pthread_mutex_lock will block (eg, go to sleep) until the lock becomes available. pthread_mutex_lock将阻塞(例如,go 进入睡眠状态)直到锁可用。 A zero return from pthread_mutex_lock means that the calling thread now has the lock. pthread_mutex_lock返回零意味着调用线程现在拥有锁。 Just make sure you release the lock when you are done working with the protected memory.只需确保在完成使用受保护的 memory 后释放锁。

Edit编辑
Here's a suggestion that will let you see that the threading mechanism is working as advertised.这是一个建议,可以让您看到线程机制正在像宣传的那样工作。

  1. Upon entry to increaseByHundred print a time-stamped message indicating entry to the function.在进入increaseByHundred时打印一条带时间戳的消息,指示进入 function。 You probably want to use C printf here rather than C++ I/O.您可能想在这里使用 C printf而不是 C++ I/O。 printf() and related functions are thread-safe. printf()和相关函数是线程安全的。 C++ 2003 I/O is not. C++ 2003 I/O 不是。
  2. After a successful return from pthread_mutex_lock print another time-stamped message indicating that a successful lock.pthread_mutex_lock成功返回后,打印另一条指示成功锁定的时间戳消息。
  3. sleep() for a few seconds and then print yet another time-stamped message prior to calling pthread_mutex_unlock() . sleep()几秒钟,然后在调用pthread_mutex_unlock()之前再打印一条带时间戳的消息。
  4. Do the same before calling pthread_exit() .在调用pthread_exit()之前做同样的事情。

One last comment: You are checking for an error return from pthread_mutex_lock .最后一条评论:您正在检查pthread_mutex_lock的错误返回。 For completeness, and because every good programmer is paranoid as all get out, you should also check the return status from pthread_mutex_unlock .为了完整起见,并且因为每个优秀的程序员都偏执,所以您还应该检查pthread_mutex_unlock的返回状态。

What about pthread_exit ? pthread_exit呢? It doesn't have a return status.它没有返回状态。 You could print some message after calling pthread_exit , but you will only reach that statement if you are using a non-compliant version of the threads library.可以在调用pthread_exit后打印一些消息,但如果您使用的是线程库的不兼容版本,您只会到达该语句。 The function pthread_exit() cannot return to the calling function. function pthread_exit()无法返回调用 function。 Period.时期。 Worrying about what happens when pthreads_exit() returns is a tinfoil hat exercise.担心pthreads_exit()返回时会发生什么是一个锡箔帽练习。 While good programmers should be paranoid beyond all get out, they should not be paranoid schizophrenic.虽然优秀的程序员应该是偏执的,但他们不应该是偏执的精神分裂症。

pthread_mutex_trylock(): pthread_mutex_trylock():

if (pthread_mutex_trylock(&mutex) == EBUSY) {
    cout << "OMG NO WAY ITS LOCKED" << endl;
}

It is also worth noting that if the mutex is not locked, it will be able to acquire the lock and then it will behave like a regular pthread_mutex_lock() .还值得注意的是,如果互斥锁没有被锁定,它将能够获得锁,然后它的行为就像一个普通的pthread_mutex_lock()

pthread_mutex_lock will normally just block until it acquire the lock, and that's why the line cout<<"\nTHREAD "<<(int)threadid<<" TRYING TO LOCK BUT CANNOT"; pthread_mutex_lock 通常只会阻塞直到它获得锁,这就是为什么行cout<<"\nTHREAD "<<(int)threadid<<" TRYING TO LOCK BUT CANNOT"; is not ran.没有跑。 You also have problems in你也有问题

while(NUMBER < 400)
     pthread_join(threads[0], &status);

because you just have 2 threads and number will never reach 400. You also want to join thread[0] on first iteration, then thread[1]...因为您只有 2 个线程,并且数量永远不会达到 400。您还想在第一次迭代时加入 thread[0],然后加入 thread[1] ...

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

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