multithreading - C# - Where is Lock Appropriate to Use in Libraries? -


i'm writing library multiple projects. , contains classes contain , manipulate data. thought should lock data while method of classes executed. thought if thread safe data manipulation must done, let higher application layer handle locking. best practice library of classes used actual applications later.

let's have class speciallist. do:

  • lock data when methods called
  • let user lock list if needs thread safety + ignore (index) exceptions user must catch them

?

if knew how .net framework class list handles same.


classes not explicitly targeted @ single- or multi-threading. helping classes kinds of uses.

if you're designing data structures , types needs have guarantee thread safety, sure, put locks , other constructs types uphold guarantees.

however, locks alone isn't enough.

take simple dictionary. let's want ensure internal data structure inside dictionary cannot corrupted multiple threads, introduce locks. however, if outside code this:

if (!dict.containskey(key))     dict.add(key, value); 

then there no guarantee here between call containskey , add, other thread hasn't added key dictionary.

as such, thread-safe types may entail more things simple locks. method can safely add key , value dictionary if it's not there, in atomic operation, , return flag telling did, may needed.

in fact, here: concurrentdictionary.tryadd.

my advice this:

  1. if need guarantees, design type thread-safe going through scenarios needs safe, , predictable, , implement specifically
  2. if don't need guarantees, don't bother doing anything, instead document type not thread-safe, leave code uses it

the .net type list not use locks in way, except few select places thread safety concern, syncroot property.

additionally, writing good thread-safe data types isn't easy. throwing in locks everywhere need them probably make more thread-safe, pay hefty penalty in terms of performance. if program doesn't need thread-safe when uses it, still pay lot of price.

writing performant thread-safe types harder, , not rely on locks (alone), instead uses things spin-waits, specific cpu instructions (some of available .net code), etc. needs highly specialized knowledge how modern cpu's execute code.

if leave thread-safety experts, , drop own types, unless absolutely need it.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -