开发者

Thread-safety in C?

开发者 https://www.devze.com 2023-02-06 09:50 出处:网络
I want to write a high performance synchronized generator in C.I want to be able to feed events to it and have multiple threads be able to poll/read asynchronously, such that threads never receive dup

I want to write a high performance synchronized generator in C. I want to be able to feed events to it and have multiple threads be able to poll/read asynchronously, such that threads never receive duplicates.

开发者_运维问答

I don't really know that much about how synchronization is typically done. Can someone give me a high level explanation of one or more techniques that I might be able to use?

Thanks!


You need a thread implementation; C does not have any built-in support for multiprocessing concepts. Threads are thus often implemented as libraries. Such a library will typically provide you with ways to synchronize the execution of multiple threads, ways to protect data, and so on.


The main concept in thread safety is the Mutex (though there is different kind of locks). It is used to protect your memory from multiple accesses and race conditions.

A good example of its use would be when using a Linked List. You can't allow two different threads to modify it in the same time. In your example, you could possibly use a linked-list to create a queue, and each thread would consume some data from it.

Obviously there are other synchronization mechanisms, but this one is (by far ?) the most important.

You could have a look at this page (and referenced pages at the bottom) for more implementation details.


Thread-safe will be the problem when there are shared variables between threads. If you don't have any shared variables, it's not a problem. Every event can be readonly and disptaching to listeners randomly.


Thread safety is achieved by using whatever synchronisation primitives the multithreading implementation provides.

Your start point would probably be a linked list of events, a lock that protects it, and every thread takes the lock, consumes one event by adjusting the pointer to the first event and then releases the lock; appending events also locks the entire list. When the list is empty, the workers exit.

From there, various optimisations are possible:

  • Caching the pointer to the last event, so appending an event to the list becomes cheaper.
  • Adding a notification mechanism so worker threads can sleep while the list is empty. Typically, this is achieved with something called a condition variable.
  • Using multiple lists, so if the first list is locked, the worker can retrieve an event from another list without having to wait for the thread that has currently locked the list.
0

精彩评论

暂无评论...
验证码 换一张
取 消