使用队列cpp的多线程请求



我试图在c++中制作多线程代理检查器,当我启动线程并锁定它时,所有线程等待直到请求完成。我试着把锁卸下来,但也没用。我使用cpr库来提出请求,文档可以在这里找到:https://whoshuu.github.io/cpr/advanced-usage.html.

可再生产的例子:

#include <stdio.h>
#include <pthread.h>
#include <iostream>
#include <queue>
#include <mutex>
#include <cpr/cpr.h>
#include <fmt/format.h>
#define NUMT 10
using namespace std; 
using namespace fmt;
std::mutex mut;
std::queue<std::string> q;
void* Checker(void* arg) {
while (!q.empty()) {
mut.lock();
//get a webhook at https://webhook.site
string protocol = "socks4";
string proxyformatted = format("{0}://{1}", protocol, q.front());

auto r = cpr::Get(cpr::Url{ "<webhook url>" },
cpr::Proxies{ {"http", proxyformatted}, {"https", proxyformatted} });
q.pop();
mut.unlock();
}
return NULL;
}

int main(int argc, char** argv) {
q.push("138.201.134.206:5678");
q.push("185.113.7.87:5678");
q.push("5.9.16.126:5678");
q.push("88.146.196.181:4153");
pthread_t tid[NUMT]; int i;
int thread_args[NUMT];

for (i = 0; i < NUMT; i++) {
thread_args[i] = i;
pthread_create(&tid[i], NULL, Checker, (void*) &thread_args);
}
for (i = 0; i < NUMT; i++) {
pthread_join(tid[i], NULL);
fprintf(stderr, "Thread %d terminatedn", i);
}
return 0;
}

提前感谢。

我建议为您的队列实现一个封装类,它将隐藏互斥锁。

该类可以提供push(std::string s)bool pop(std::string& s),如果队列不为空或不为假,则返回true并填充s。然后你的工作线程可以简单地循环

std::string s;    
while(q.pop(s)) {
...
}

最新更新