C ++多线程互斥锁锁定分段错误

时间:2019-04-19 00:16:08

标签: c++ multithreading mutex readwritelock

**这是针对大学课程,我实际上并不是在尝试破解密码** 下面是我的源代码,但实际上我想发生的是父进程将密码排队到std :: list <> tryList中。然后,子线程从队列的最前面开始抓取,当前仅打印出该值。

如下面的代码所示,我尝试使用std :: mutex在弹出前端时阻止tryList,但是两个线程同时吹过锁并从前端读取。然后其中之一是分段错误,程序崩溃。

段错误的特定代码段是...

mutex.lock();
password = attemptList.front();
attemptList.pop_front();
size = attemptList.size();
std::cout << password << std::endl;
            mutex.unlock();
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <string>
#include <iostream>
#include <chrono>
#include <shared_mutex>
#include <unistd.h>
#include <sys/ipc.h>
#include <mutex>
#include <sys/shm.h>
#include <sys/wait.h>
#include <thread>
#include <vector>
#include <algorithm>
#include <list>

#define MAX_LENGTH 4
#define MAX_QUEUE_SIZE 1000
#define CHARACTER_LIST "abcdefghijklmnopqrstuvwxyz"

void enqueue_passwords(const std::string& charList);
void bruteforce();
void do_join(std::thread& t);
void join_all(std::vector<std::thread>& v);

std::list<std::string> attemptList;
std::mutex mutex;
bool conclude = false;

int main(int argc, char* argv[]) {
    auto start = std::chrono::high_resolution_clock::now();

    int index;
    std::vector<std::thread> threads;
    for (index = 0; index < 2; index++) {
        threads.emplace_back(std::thread(bruteforce));
    }

    enqueue_passwords(CHARACTER_LIST);

    join_all(threads);

    auto stop = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
    std::cout << duration.count() << " milliseconds" << std::endl;

    return 0;
}

void bruteforce() {
    double size = 0;
    std::string password;

    while (!conclude) {
        do {
            mutex.lock();
            size = attemptList.size();
            mutex.unlock();

            if (size == 0) {
                usleep(300);
            }
        } while (size == 0);

        while(size != 0) {
            mutex.lock();
            password = attemptList.front();
            attemptList.pop_front();
            size = attemptList.size();

            std::cout << password << std::endl;
            mutex.unlock();
        }
    }
}

void enqueue_passwords(const std::string& charList) {
    const int maxLength = MAX_LENGTH;
    const int charListLength = charList.length();

    char password[MAX_LENGTH + 1];
    memset(password, '\0', MAX_LENGTH + 1);

    int index;
    int number;

    double permutations = 0;

    double count = 0;
    double passPosition = 0;
    double size = 0;

    // Calculate number of permutations possible
    for (index = 0; index < maxLength; index++) {
        permutations += charListLength * powl(charList.length(), maxLength - index - 1);
    }

    std::cout << "Permutations:  " << permutations << std::endl << std::endl;

    password[0] = charList[0];
    while (count < permutations) {
        do {
            mutex.lock();
            size = attemptList.size();
            mutex.unlock();

            if (size > MAX_QUEUE_SIZE) {
                usleep(250);
            }
        } while (size > MAX_QUEUE_SIZE);

        // Loop over current set of characters ,changing the last one
        for (index = 0; index < charListLength; index++) {
            password[int(passPosition)] = charList[index];

            // ENQUEUE HERE //
            mutex.lock();
            attemptList.push_back(std::string(password));
            mutex.unlock();
            // ENQUEUE HERE //

            if (count > permutations) {
                break;
            }
            count++;
        }

        // Iterate over remaining indexes, except for the last one
        for (number = int(passPosition); number >= 0; number--) {
            if (password[number] != charList[charListLength - 1]) {
                password[number]++;
                break;
            } else {
                if (number == 0) {
                    passPosition++;
                    for (index = 0; index < passPosition + 1; index++) {
                        password[index] = charList[0];
                    }
                    break;
                }
                password[number] = charList[0];
            }
        }
    }

    conclude = true;
}

void do_join(std::thread& t) {
    t.join();
}

void join_all(std::vector<std::thread>& v) {
    std::for_each(v.begin(), v.end(), do_join);
}

2 个答案:

答案 0 :(得分:3)

   do {
        mutex.lock();
        size = attemptList.size();
        mutex.unlock();

        if (size == 0) {
            usleep(300);
        }
    } while (size == 0);

抛开效率问题,此代码将锁定互斥锁,获取列表的大小并解锁互斥锁。

比方说,该线程得出的结论是列表的大小为1,因此该线程离开了while循环。 size为1。此时,列表恰好只有一个值。 while循环终止。

但是,在进一步处理之前,您的其他线程之一在此时同时执行完全相同的操作:它锁定互斥锁,获取列表的大小,解锁互斥锁,确定该列表为1,并且也退出其while循环,就像第一个线程一样。让我们看看接下来会发生什么,现在我们两个线程都在这里:

    while(size != 0) {
        mutex.lock();
        password = attemptList.front();
        attemptList.pop_front();

好,现在第一个线程醒来,进入while循环,锁定互斥锁,获取列表中唯一的条目,将其从列表中删除,列表现在为空。

您的第二个线程现在执行相同的操作,并在其mutex.lock()调用中阻塞,因为第一个线程已将其锁定。

第一个线程最终将互斥锁解锁。现在第二个线程继续;它锁定了互斥锁,并且在列表不为空的错觉下进行操作,因为它仍然认为其大小为1(因为正是锁定时的大小),因此在初始while循环中尝试执行从空列表中删除第一个元素。

未定义的行为。

这是导致崩溃的原因。

答案 1 :(得分:0)

如Sam所述,双重互斥锁使您的代码效率降低,并同时创建了竞争条件。可能的解决方案是(用于提取数据的内部循环):

while( !conclude ) {
    std::string password;
    {
        std::lock_guard<std::mutex> lock( mutex );
        if( attemptList.size() ) {
           password = std::move( attemptList.front() );
           attemptList.pop_front();
        }
    }
    if( password.empty() ) {
        usleep(300);
        continue;
    }
    // work with password here
}

这样一来,您只需锁定一次互斥锁,并在互斥锁仍处于锁定状态时提取数据,以防止出现竞争状况并提高效率。对于将代码推送到队列,应该执行相同的操作。

该代码应该可以工作,但是在这种情况下,睡眠不是同步线程的最佳方法,您应该使用std::condition_variable。并且您的conclude变量应在互斥锁下进行检查,或者至少应为std::atomic<bool>