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
46
votes
5answers
14k 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 ...
37
votes
1answer
3k 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 ...
31
votes
1answer
16k 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, ...
29
votes
0answers
883 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 ...
22
votes
2answers
14k 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 ...
21
votes
2answers
24k views

Thread-safe Singleton class

I have created this class to simulate a thread-safe Singleton. Have I missed anything? ...
20
votes
3answers
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 ...
20
votes
1answer
22k 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 ...
19
votes
1answer
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-...
18
votes
2answers
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 ...
17
votes
2answers
36k 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. ...
15
votes
3answers
36k 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 ...
15
votes
4answers
2k 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 ...
15
votes
5answers
16k views

Java blocking queue

...
15
votes
1answer
5k 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 ...
14
votes
4answers
28k 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,...
14
votes
1answer
627 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 ...
13
votes
2answers
478 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 ...
12
votes
2answers
31k 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 ...
12
votes
1answer
7k views

Thread-Safe Integer Sequence

I would like to give an Integer to whatever demands it. For that I use the following code ...
11
votes
3answers
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 ...
11
votes
1answer
541 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 ...
11
votes
2answers
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 ...
11
votes
1answer
6k 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 ...
11
votes
1answer
13k views

Thread-safe lock-free counter

I was using such code: ...
11
votes
1answer
145 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 ...
11
votes
1answer
1k 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 ...
11
votes
2answers
197 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 ...
10
votes
2answers
5k 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 ...
10
votes
2answers
2k 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 ...
10
votes
2answers
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 ...
10
votes
2answers
5k 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: <...
10
votes
1answer
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 ...
10
votes
2answers
730 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. ...
10
votes
1answer
1k views

Utilization of the Multiton pattern

See Wikipedia - Multiton Pattern for details on the intent. Here's the class: ...
9
votes
4answers
2k 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 ...
9
votes
2answers
29k 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 ...
9
votes
1answer
790 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 ...
9
votes
2answers
9k 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 ...
9
votes
3answers
622 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 ...
9
votes
1answer
3k 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. ...
8
votes
3answers
3k views

Simple generic double buffer pattern

I wrote a small generic implementation of a simple generic double buffer pattern, and I was wondering if it's actually thread safe or can be improved in any way. Note: The specific part that I'm ...
8
votes
1answer
44k 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 ...
8
votes
3answers
158 views

ConcurrentThrottledList - Will this implementation be thread safe?

I want a thread safe list with a max item count, will the following implementation correctly provide this? ...
8
votes
2answers
2k views

Portable periodic/one-shot timer thread - follow-up

This is a much improved version (I hope) of code in this previous code review of mine. I have: renamed several things. Are the names good? made it lazily start the worker thread only after the first ...
8
votes
2answers
2k views

Using keywords async/await in database queries (Windows Phone 8)

I have a local database in Windows Phone 8 app. The app includes a lot of queries to the database and I don't want bad effect on the responsiveness of UI. For ...
8
votes
1answer
401 views

Dynamically extensible threadpool implementation in C

Purpose For my recent project, I needed a thread pool. I saw a lot of implementations at GitHub, but most of them were quite complicated. With complication comes performance penalty. Most importantly,...
7
votes
3answers
10k views

Dining philosophers problem in C++11

Is this implementation correct? Do you find any threading problem? Also, what parts of the code can be changed to be more C++11-ish? ...
7
votes
4answers
800 views

Caching Color-Bitmaps as MemoryStreams

I am in the need to cache Bitmap's in a memory-optimized way because the API I am building will need to process many colored ...
7
votes
2answers
1k views

Synchronized implementation of a bank account in Java

I am trying to implement a bank account with Java in a thread safe way. My code looks like: ...