-1
基本上我以前没有做过多线程编程。从概念上讲,我意识到这一点。多线程结果放慢
因此开始使用随机数生成编码。代码正在工作,但它产生的结果比单线程程序慢。所以想知道我的代码中的漏洞以及如何提高性能。
所以如果我tr随机生成1-1500个数字,使用单线程和10个线程(或5个线程)。单线程执行速度更快。线程切换或锁定似乎需要时间。那么如何处理呢?
pthread_mutex_t map_lock;
std::set<int> numSet;
int randcount=0;
static void *thread_fun (void *arg)
{
int randNum= *(int *)arg;
int result;
std::set<int> findItr;
while (randcount != randNum -1) {
result = rand()%randNum;
if (result == 0) continue;
pthread_mutex_lock (&map_lock);
const bool is_in = (numSet.find (result) != numSet.end());
if (!is_in)
{
numSet.insert (result);
printf (" %d\t", result);
randcount++;
}
pthread_mutex_unlock (&map_lock);
}
}
你是怎么运行的?这是编译为一些编程语言? –
多线程的目的不是要更快地做一件事,而是要同时做很多事情。你的例子是尝试多线程的一个不好的理由,你应该做(例如)到服务器的多重连接。这些不是连续的过程,而是并行的。 – KevinDTimm
以上是用C++语言编写的部分代码。哪些获取使用pthread_create创建的每个线程的调用。 – Sach