如何在完成工作后停止所有pthread
How to stop all pthreads when one has completed its work?
我正试图创建一个代码来强制执行随机字符串,但在一个线程上运行它会花费太长时间(正如预期的那样)。我正在摆弄pthreads,这就是我想到的:
void*
bruteForce ( void* ARGS )
{
args *arg = ( args * ) ARGS;
string STRING= arg->STRING;
string charSet = arg->charSet;
string guess = arg->guess;
char c;
int size;
int pos;
int lenght;
int j = 0;
char CHAR[STRING.length ( )];
size = charSet.length ( );
do
{
for ( j = 0; j < STRING.length ( ); j++ )
{
pos = rand ( ) % size;
CHAR[j] = charSet[pos];
guess = string ( CHAR );
//cout << guess[j];
}
//cout << guess << endl;
}
while ( STRING!= guess );
}
int
main ( int argc, char** argv )
{
srand ( ( unsigned ) ( time ( NULL ) ) );
const int NUMBER_OF_THREADS = 10;
args arg;
ifstream myFile;
string STRING;
string charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string guess;
pthread_t threads[NUMBER_OF_THREADS];
void* status;
arg.charSet = charSet;
arg.STRING= STRING;
char c;
int size;
int pos;
int lenght;
int j = 0;
myFile.open ( "string.txt" );
getline ( myFile, STRING);
size = charSet.length ( );
int rc;
//Creating threads for cracking the string
for ( int i = 0; i < NUMBER_OF_THREADS; i++ )
{
rc = pthread_create ( &threads[i], NULL, bruteForce, ( void* ) &arg );
if ( rc )
{
cout << "Couldnt create thread";
exit ( 1 );
}
}
//Joining threads
for ( int i = 0; i < NUMBER_OF_THREADS; i++ )
{
rc = pthread_join ( threads[i], &status );
if ( rc )
{
cout << "thread number " << i << " was unable to join: " << rc << endl;
exit ( 1 );
}
}
}
现在,我需要某种方式来发出信号,表明其中一个线程已经正确猜测了字符串,并终止其他线程。我阅读了pthread库的一些文档,但找不到任何内容。感谢您的帮助。
PS:我知道暴力算法还不是最好的。
只要你不想让你的程序在找到答案后再运行,你就可以从找到答案的线程调用exit(0)。
do
{
// ...
}
while ( STRING!= guess );
std::cout << guess << std::endl;
std::exit(0);
笨拙但在您的情况下可行:
在全局范围中添加DONE标志。当任何线程找到结果时设置它。使每个线程的循环依赖于标志。
bool DONE=false; // set to true to stop other threads
void*bruteForce ( void* ARGS )
{ ...
do
{ <try a string>
}
while ( !DONE && STRING!= guess );
DONE=true; // set redundantly but that doesn't hurt
}
您的主程序仍然可以进行连接以收集完成的pthread,然后继续对猜测的答案进行任何工作。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- pthread只有在线程数量较少时才可以正常工作
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 将工作与固定数量的螺纹之间的工作和pthread之间的分配
- 如何在完成工作后停止所有pthread
- pthread中的线程在一些迭代之后停止工作
- 为什么在pthread-win32中主线程比工作线程慢
- pthread程序导致Linux机器出现分段错误.在Cygwin64上工作良好
- PThread健壮互斥不工作