John Livingston John Livingston - 9 months ago 53
C Question

Multithreading - how to stop all threads if condition is met?

EDIT : I cannot use mutex or sleep() or any type of waiting as we're fairly new to threads in C.

For my assignment I'm to make a bruteforce password cracker using threads. The idea is that I have the hash and salt of a password so I have use a combination of the alphabet A-Z, a-z, 0-9 and encrypt it using the crypt_r function and compare it with the hash and salt I have.

I created 2 threads, one that just checks for lowercase letters and the second one that checks all the letters of the alphabet.

My problem is that once the lowercase thread finds the password it gives it but the second thread continues running in the background.

How can I stop the second thread without using any global variables?

Here's how I go about the thread joins :

for (int i = 0; i < nbThread; ++i) {
pthread_join(tabThread[i], NULL);
pthread_join(tabThread2[i], NULL);

Thank you for your time and help!

usr usr
Answer Source

You don't have to use pthread_join() calls unless you want to do something after the threads exit. It's a convenience function, not a necessity. You can let the main thread exit with pthread_exit() (without any pthead_join() calls) and the other two threads can continue until either of them succeeded. If either of your threads find the password then you can simply exit (using _exit() or _Exit()) the process and the other thread will naturally be terminated on process exit.