Questions tagged [thread-safety]

A piece of code is thread-safe if it only manipulates data structures in a way that allows consistent execution of this code by multiple threads.

Filter by
Sorted by
Tagged with
49 votes
5 answers
15k views

Thread-Safe and Lock-Free - Queue Implementation

I was trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently. Would you ...
Hosam Aly's user avatar
  • 1,301
40 votes
1 answer
4k views

Recursive shared_mutex implementation

I found myself in need of a Readers-Writer mutex. With C++17 TR2 support not yet available in our compiler, I set out to implement std::shared_mutex so that we have ...
Emily L.'s user avatar
  • 16.5k
36 votes
1 answer
21k views

Extension methods to make ConcurrentDictionary GetOrAdd and AddOrUpdate thread safe when using valueFactory delegates

The ConcurrentDictionary<T,V> in .NET 4.0 is thread safe but not all methods are atomic. This points out that: ... not all methods are atomic, ...
Adam Spicer's user avatar
36 votes
1 answer
1k views

Making a generic NSMapTable replacement written in Swift thread-safe

This is a follow-up to this question. While discussing some details about the code I posted there, I came upon a problem with thread-safety. After searching and trying different things, I reached a ...
Alex's user avatar
  • 581
24 votes
2 answers
15k views

Thread pool worker implementation

As an exercise in using C++11 features I decided to make a thread pool class. I would like to have a review on the code with focus on: Standards compliance / Portability issues / Best practices ...
Emily L.'s user avatar
  • 16.5k
22 votes
5 answers
36k views

A TaskScheduler that always run tasks in a specific thread

The following is an TaskScheduler that always run tasks in a thread it maintains. When created, a name of the thread was specified. Once you schedule the first task,...
Earth Engine's user avatar
22 votes
2 answers
57k views

Creating a thread-safe list using a Lock object

Will this code qualify for a truly thread-safe list? It is using the Lock object. ...
Mrinal Kamboj's user avatar
22 votes
1 answer
25k views

Thread-safe concurrent FIFO queue in C++

Is this the correct way to implement a thread-safe concurrent FIFO queue in C++? It requires passing unsigned char* arrays of binary data. Thread Safe Concurrent ...
PerracoLabs's user avatar
22 votes
2 answers
25k views

Thread-safe Singleton class

I have created this class to simulate a thread-safe Singleton. Have I missed anything? ...
q0987's user avatar
  • 321
21 votes
3 answers
16k views

Determining if a connection has been made to a communications device

I am unsure if my use of Monitor.Wait and Monitor.Pulse is correct. It seems to work alright, but there is a nagging doubt I am ...
Andy's user avatar
  • 343
20 votes
1 answer
1k views

Messed up Elevator Management System

In light of our current community-challenge I decided to build an Elevator Management System. Initially I intended to program the EMS like a real-time operating system and the elevators as finite-...
Mast's user avatar
  • 13.1k
18 votes
2 answers
2k views

Thread-safe prime number source

I am working on some multi-threaded code that requires a prime-number source. The following code keeps an array of primes in memory, extending it as needed. It works in the 'int' domain, being ...
rolfl's user avatar
  • 97.3k
16 votes
4 answers
3k views

Throttling class

The idea of this class is that several threads are sending data over a network and each thread are sharing the same instance of this class and before sending N bytes over the network each thread is ...
skyde's user avatar
  • 193
16 votes
1 answer
6k views

Lock-free multiple-consumer multiple-producer queue

The code below implements an intrusive lock-free queue that supports multiple concurrent producers and consumers. Some features: Producers and consumers work on separate ends of the queue most of ...
Javier Blazquez's user avatar
15 votes
3 answers
40k views

Generic, thread-safe MemoryCache manager for C#

Using this question as a base, and using some of the advice in the answers, I wanted to build out something that would be generic, thread-safe, and easy to use for at least one current and several ...
egandalf's user avatar
  • 253
15 votes
5 answers
17k views

Java blocking queue

...
a3user's user avatar
  • 151
15 votes
2 answers
1k views

Concurrency limit map in Go

Task: per host concurrency limits for web crawler (map[string]Semaphore). I considered chan struct{} (chan bool) approach, but ...
temoto's user avatar
  • 251
15 votes
1 answer
1k views

C++11 Threadpool

I have developed a threadpool using the standard c++11 features and am looking for feedback. Right now I think the implementation is pretty solid, but as I recently learned about multithreading I'm ...
amc176's user avatar
  • 345
13 votes
2 answers
5k views

Implementation of a Thread Pool in C++

I wanted to implement a thread pool to test my knowledge of various modern C++ features. The end result could be better, but I need a review as I'm not sure about delicate things especially regarding ...
KeyC0de's user avatar
  • 233
13 votes
1 answer
9k views

Thread-Safe Integer Sequence

I would like to give an Integer to whatever demands it. For that I use the following code ...
Manuelarte's user avatar
13 votes
2 answers
572 views

Thread-safe large text buffer

This is part of one of my projects called largetext, which actually stemmed from a question on Stack Overflow. The goal is to provide access to a very large text file as a ...
fge's user avatar
  • 1,743
12 votes
2 answers
35k views

Add/Remove items thread-safely in List<T>

Recently I had to lock collections (of type List<T>) when items were added or removed. Because several collections were used in given code instead of creating ...
Leri's user avatar
  • 287
12 votes
1 answer
18k views

Thread-safe lock-free counter

I was using such code: ...
Oleg Vazhnev's user avatar
12 votes
2 answers
229 views

Thread safety/Transaction enforcer

I have some legacy classes written without thread safety in mind. Instances of these classes are now being accessed in a multithreaded context in a thread-un-safe manner. Cue chaos. To fix this I ...
Emily L.'s user avatar
  • 16.5k
11 votes
1 answer
9k views

Concurrent HashSet

I've recently been using HashSet and locking on each method, I found this to not only be a lot of work (was using it in a lot of places) but I started to see inconsistency in my code. I later decided ...
Adam Jones's user avatar
11 votes
3 answers
1k views

Memory cache implementation

I have created an open source memory cache called cachew and can be found here: cachew. I would like your help to make it better. Regarding the class Cache or its ...
Jakob's user avatar
  • 964
11 votes
1 answer
607 views

Multithreading class for asynchronous usage of a custom client/server exchange

I've thrown everything I can at this, and I can't get it to lock or crash. My hope is that I have applied the principles correctly. I write client apps in JavaScript, and this is only the 3rd .NET ...
blaze4218's user avatar
  • 353
11 votes
2 answers
2k views

Thread-safe session manager

Expected behavior of the code below: There will be one static SessionManager accessed by many threads. Multiple calls to ...
Ocelot20's user avatar
  • 1,883
11 votes
1 answer
7k views

Timer to poll a Delegate

This is a followup to this where I was initially using a single thread and Thread.Sleep() to poll a delegate. I was recommended to use a timer and the ...
Alain's user avatar
  • 472
11 votes
1 answer
318 views

C++ thread-safe averaging

Although having very little C++ experience, I was tasked to implement several statistics objects that are safe to be asynchronous accessed by different threads, that collect data in relatively small ...
lunej.le's user avatar
  • 213
11 votes
3 answers
5k views

C++ Threaded Logger

What is it? It's a fairly simple logger which utilises a thread. How it works Note: this a pretty terrible explanation, perhaps it would be easier to look at the code. The logger class is a ...
seepp's user avatar
  • 113
11 votes
1 answer
2k views

Do not share same socket between two threads at the same time

I have a code in which I am dealing with sockets and I need to make sure that I don't share same socket between two threads. In my below code, I have a background thread which runs every 60 seconds ...
david's user avatar
  • 1,647
11 votes
1 answer
1k views

Utilization of the Multiton pattern

See Wikipedia - Multiton Pattern for details on the intent. Here's the class: ...
OldCurmudgeon's user avatar
10 votes
4 answers
9k views

AsyncDictionary - Can you break thread safety?

This class is an Async/Await wrapped Dictionary. Of course it doesn't technically implement IDictionary, but the functionality is basically the same as an IDictionary. It achieves similar ...
Christian Findlay's user avatar
10 votes
2 answers
6k views

Using synchronized blocks and volatile variables to ask a Java thread to terminate gracefully

Edit: Just to clarify, this isn't my original code, I've simplified it to make it smaller/easier to understand what I'm trying to do. It's my first time working with threads in Java, and I was ...
Lucas AM's user avatar
  • 103
10 votes
2 answers
3k views

Will this Circuit Breaker catch fire?

I was going to post this code as an answer to a recent question, but I wrote this code a little while ago (like, a year ago; if I recall correctly I wrote this after reading this article) and I'd like ...
Mathieu Guindon's user avatar
10 votes
1 answer
53k views

Writing to file in a thread safe manner

I'm writing Stringbuilder to file asynchronously. This code takes control of a file, writes a stream to it and releases it. It deals with requests from asynchronous operations, which may come in at ...
Nathan Cooper's user avatar
10 votes
2 answers
7k views

Abuse/Misuse of C# BackgroundWorker?

I have finished a program, and it does what I want it to do, but I feel I am "doing it wrong", even though it's seemingly efficient enough. I have prepared a small example of what I feel I am handling ...
MrFreeman's user avatar
  • 103
10 votes
2 answers
30k views

Synchronous and asynchronous behavior for client

I am working on a project in which I am supposed to make synchronous and asynchronous behavior of my client. The customer will call our client with a userId and we ...
david's user avatar
  • 1,647
10 votes
3 answers
32k views

Correct way to delete elements from a ConcurrentDictionary with a predicate

I have written a caching wrapper class for ConcurrentDictionary. Basically it has a timer that checks if items are expired and removes them. Since ConcurrentDictionary does not have RemoveAll method ...
Ufuk Hacıoğulları's user avatar
10 votes
1 answer
2k views

Platform independant thread pool

v2 of this question is here and v3 is here To get a better understanding of C++11/C++14, I thought I would develop a thread pool, even if it has been done to death! The only dependency outside of ...
Tom Myles's user avatar
  • 432
10 votes
2 answers
778 views

Sending SMS through twilio from play framework

I am trying to send SMS using Twilio with Scala 2.10 in Playframework 2.2, but this code is looking odd to me, maybe due to lots of conditions. I'm sure it needs some important reviews. ...
Govind Singh Nagarkoti's user avatar
10 votes
1 answer
4k views

Portable C++ boost::interprocess::mutex

I was looking for long time around to have a portable robust solution for multiprocessing synchronization. Who touche this things know that good solution are boost::iterprocess named sync objects. ...
Ladislav's user avatar
  • 101
9 votes
3 answers
11k views

Implementing an asynchronous mutex in C#

I wrote a simple synchronization primitive that I can use with async operations on an external REST service so that I don't call it twice from different threads and have one call fail due to not ...
Tim Lovell-Smith's user avatar
9 votes
1 answer
3k views

A thread-safe priority queue keeping its elements unique

This class is intended to be used in situations where queue.Queue does not suffice, because the following two properties are needed. Every item in the queue can ...
Tobias Hermann's user avatar
9 votes
2 answers
7k views

Simple dispatcher implementation

I need a simple dispatcher implementation(invoke methods on one thread from many threads) once you dispatch method curent thread should wait for results, so I'm thinking about something like this: <...
Selvin's user avatar
  • 249
9 votes
2 answers
10k views

Simple C++ thread pool

I wrote a minimalistic thread pool using some C++11 features. I've used it on two projects so far and it has worked fine, but when I ran the code on my laptop, I believe that my thread pool might be ...
Nelarius's user avatar
9 votes
2 answers
961 views

Multithreaded bogosort in Rust

For some quick context, I'm fairly new to Rust and decided to give myself a difficult-but-attainable task of implementing a sorting algorithm. I chose bogosort (or stupid-sort, shuffle-sort, whatever ...
LambBrainz's user avatar
9 votes
2 answers
16k views

Thread-safe std::map accessor

After learning that std::map containers are not inherently atomic and therefore not thread-safe (check out this related Stack Overflow question and usage example), ...
BigMacAttack's user avatar

1
2 3 4 5
11