简体   繁体   English

C-使用PThreads时更快地锁定整数

[英]C - faster locking of integer when using PThreads

I have a counter that's used by multiple threads to write to a specific element in an array. 我有一个计数器,多个线程用于将其写入数组中的特定元素。 Here's what I have so far... 到目前为止,这就是我所拥有的...

int count = 0;
pthread_mutex_t count_mutex;

void *Foo()
{
    // something = random value from I/O redirection
    pthread_mutex_lock(&count_mutex);
    count = count + 1;
    currentCount = count;
    pthread_mutex_unlock(&count_mutex);
    // do quick assignment operation. array[currentCount] = something
}
main()
{
    // create n pthreads with the task Foo
}

The problem is that it is ungodly slow. 问题在于它运行缓慢。 I'm accepting a file of integers as I/O redirection and writing them into an array. 我接受整数文件作为I / O重定向并将其写入数组。 It seems like each thread spends a lot of time waiting for the lock to be removed. 似乎每个线程都花费大量时间等待删除锁。 Is there a faster way to increment the counter? 有没有更快的方法来增加计数器?

Note: I need to keep the numbers in order which is why I have to use a counter vs giving each thread a specific chunk of the array to write to. 注意:我需要按顺序保留数字,这就是为什么我必须使用计数器而不是给每个线程写入数组的特定块的原因。

You need to use interlocking. 您需要使用联锁。 Check out the Interlocked* function on windows, or apple's OSAtomic* functions, or maybe libatomic on linux. 在Windows上查看Interlocked *函数,或者在Apple上查看 Apple的OSAtomic *函数,或者在Linux上查看libatomic

If you have a compiler that supports C++11 well you may even be able to use std::atomic . 如果您的编译器很好地支持C ++ 11,则您甚至可以使用std :: atomic

Well, one option is to batch up the changes locally somewhere before applying the batch to your protected resource. 好吧,一种选择是在将批处理应用于受保护的资源之前,在本地某处批处理更改。

For example, have each thread gather ten pieces of information (or less if it runs out before it's gathered ten) then modify Foo to take a length and array - that way, you amortise the cost of the locking, making it much more efficient. 例如,让每个线程收集十个信息(如果在收集十个信息之前用尽,则更少),然后修改Foo以获取长度和数组-这样,您可以分摊锁定的成本,从而提高锁定效率。

I'd also be very wary of doing: 我也会非常谨慎:

// do quick assignment operation. array[currentCount] = something

outside the protected area - that's a recipe for disaster since another thread may change currentCount from underneath you. 保护区之外 -这是灾难的currentCount ,因为另一个线程可能会改变您下面的currentCount That's not a problem if it's a local variable since each thread will have its own copy but it's not clear from the code what scope that variable has. 如果它是局部变量,那不是问题,因为每个线程都有自己的副本,但是从代码中尚不清楚该变量的作用域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM