109: (Default)
[personal profile] 109
гы, а слово volatile, оказывается, применимо только к членам. а если я передаю в другой тред кложу, которая меняет локальную переменную, то что я должен делать?



delegate void Callback();

class ThreadData { internal object Data; internal Callback OnExit; }

void FanOut(object[] datas) 
{
  int threadCount = datas.Length;
  foreach (object data in datas) 
  {
    ThreadData threadData = new ThreadData(data);
    threadData.OnExit = delegate { Interlocked.Decrement(ref threadCount); };
    ThreadPool.QueueUserWorkItem(ThreadProc, threadData);
  }
}

(no subject)

Date: 2008-04-25 10:45 am (UTC)
From: [identity profile] faceted-jacinth.livejournal.com
Интересный вопрос!
В результате вдумчивого чтения документации у меня создалось впечатление, что использование любой synchronization-related конструкции как бы говорит компилятору, что надо всё релоаднуть, а volatile нужен только когда этих конструкций нет.

Но в явном виде и с перечислением штук, считающихся относящимися к синхронизации, я не нашёл ничего. Сообщи, если тебе вдруг повезёт больше, пожалуйста.

(no subject)

Date: 2008-04-25 08:17 pm (UTC)
From: [identity profile] 109.livejournal.com
well, I guess I had to show more code to make the point. after "foreach" there is a while (threadCount > 0) loop that reads from the queue data produced by threads. and sometimes this loop doesn't end. because, I believe, of some [incorrect] optimizations compiler makes.

my another point is that with closures local variables lose their "locality" and therefore there is no sense to make "volatile" only applicable to members.

(no subject)

Date: 2008-04-25 08:22 pm (UTC)
From: [identity profile] faceted-jacinth.livejournal.com
А, ясно. Но ты мог бы и посмотреть в код дизассемблером, чтобы быть уверенным. Проще всего -- через постановку брейкпоинта.


Да, было бы неплохо, если б они добавили такую штуку.


Пока придётся руками повторять работу компилятора по превращению кложура в класс и ставить волатиль там, видимо.

(no subject)

Date: 2008-04-30 09:52 am (UTC)
From: [identity profile] faceted-jacinth.livejournal.com
Кстати!
For more information, see the following sections in the C# Language Specification:

3.10 Execution order

10.5.3 Volatile fields

Оно, оказывается, вообще всё не так, как кажется! volatile не конкретную переменную заставляет релоадиться, а вообще всё -- при доступе к этой переменной. То есть, насколько я понимаю, тебе достаточно в любое место вставить lock(this) {} (именно так, пустой), это сгенерит critical execution point и всё заработает.

(no subject)

Date: 2008-05-01 07:55 am (UTC)
From: [identity profile] 109.livejournal.com
Monday and Tuesday I was attending Jeffrey Richter classes (yes, THAT Jeffrey Richter), and he told me to use some Thread.Read() or something that sounds like it.

(no subject)

Date: 2008-05-01 11:04 am (UTC)
From: [identity profile] faceted-jacinth.livejournal.com
Thread.VolatileRead
Yes, that's the best solution, thanks.

Profile

109: (Default)
109

March 2019

S M T W T F S
     12
3456789
101112131415 16
17181920212223
24252627282930
31      

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags