C# Multithreading -
C# Multithreading -
okay. want have 2 threads running. current code:
public void foo() { lock(this) { while (stopthreads == false) { foreach (var acc in mylist) { // process stuff } } } } public void bar() { lock(this) { while (stopthreads == false) { foreach (var acc in mylist) { // process stuff } } } }
both accessing same list, problem first thread "foo" not releasing lock guess; because "bar" starts when "foo" done. thanks
yes, that's how lock designed work.
the lock keyword marks statement block critical section obtaining mutual-exclusion lock given object, executing statement, , releasing lock.
mutual-exclusion means there can @ 1 thread holds lock @ time.
locking on bad thought , discouraged. should create private object , lock on instead. solve problem lock on 2 different objects.
private object lockobject1 = new object(); private object lockobject2 = new object(); public void foo() { lock (lockobject1) { // ... } } public void bar() { lock (lockobject2) { // ... } }
alternatively reuse same lock move within loop each loop has chance proceed:
while (stopthreads == false) { foreach (var acc in mylist) { lock (lockobject) { // process stuff } } }
however suggest spend time understand going on rather reordering lines of code until appears work on machine. writing right multithreaded code difficult.
for stopping thread recommend article:
shutting downwards worker threads gracefully c# multithreading locks
Comments
Post a Comment