How to Increment/Decrement A Variable In A Thread Safe Manner

Sometimes it will be necessary to increment or decrement a variable in a atomic manner so that no other thread can affect it while being incremented/decremented. The complex mutexes and critical sections can do the trick. Still, there is a single line API which does the same and it is

LONG InterlockedIncrement(LONG volatile* Addend)

(InterlockedDecrement for decrementing the value).

For example,

LONG myNo = 10;
LONG returnValue = InterlockedIncrement(&myNo);

will make

myNO = 11 and returnValue = 11.


38 Responses to How to Increment/Decrement A Variable In A Thread Safe Manner

  1. zakimirza says:

    You can also use Interlocked.Increment method in .NET for the same purpose. Its in in the System.Threading namespace.

  2. cppkid says:

    Thanks a lot. Keep watching the blog.

  3. acerymnpype says:

    My PC worked slowly, too much errors. Help me, please to fix buggs on my computer.
    My operation system is Windows 2003.
    With best regards,

  4. SkerakKicic says:

    Доброго времемяни суток!
    Офигеть, но ведь в самом деле – женюсь!
    вот как Вы на это смотрите?

    з.ы. сорри если не туда написал, имоции 🙂

  5. dombi says:

    Elements of Garden Sketch out It is unquestionably counterbalance to divulge that diverse rich garden lay-outs started to engage model on a plan board. At the beginning-although it require be known what stripe of garden is envisaged and some of the features to be included-it is not exigent to create any definite ideas on organize but more wisely to strengthen essential on measuring and recording all the existing features so that an unerring bird’s-eye way of thinking of the garden can be strained to scale. There is no other route of seeing the arrondissement as a sound and the assertion of the residence satisfactorily. It is from this grade that ideas through despite the design of the garden and planting plans can be formulated. THE AT COCK CROW PLANNING POINT It is freakish into a plot of get to be systematically rectangular and the sides are time again unequal in length. The essential aids at this early organize are a measuring tape, at least 6oft(i8m) in to the fullest extent a finally; a metal spike to safeguard the ambivalent, and a wide writing pad. Constant without the promote of a surveyor’s more decorate apparatus, a pretty accurate get a bird’s eye view of can be made to clinch the supervising of the boundaries and the disposition of the ancestry germane to these, via taking the metage from a corner of the parliament or edifice in succession with the palisade to the frontiers (Fig.i). If the identical function is repeated on the yet side from another corner it transfer escort if the frontiers is at an angle or uniform to the building.A fresh check can be made by fixing the stripe in joined of the far corners of the locale and operation along the bottom bounds until the rampart of the building-which would be seen al honourable angles-disappears from view. If this depth is compared with the others made earlier the points on the boundary should match at the three places. If it is inescapable to line a sight assortment across a report of land from a certain poin to another, it is of use to have readily obtainable 10 or more 6ft(2m) bamboo canes (manage Fig.2). The canes are then spaced, conceivably 8 or ioft(2.5 or 3m) or more asunder except for, throughout a presupposed aloofness, and when five or six canes are in position the area is made exactly regular by way of adjusting the intermediary canes between the two end ones. When a sighting is made from the furthest end, only the nearest cane settle upon then be visible. The position of a tree or other permanen features can be recorded alongside measuring from the object in without a doubt to two points which are separated by way of a known distance; this could be two corners of the house. The measurements are then transcribed to wrapping paper with the use of a compass and the estate marked where the arcs cross. Having notable as various details as practical that are able to be useful, a plan of the area can be exhausted to scale. It can large be assumed that if the create appears to be profitably on instrument it leave purposes be strategic on the site. The demand to ascertain the garden from the word go in layout construct applies uncommonly if the beds an< contours issue a curved outline.

  6. booneeseede says:

    NFL Picks

    unshackle nfl picks is proud to be your begetter payment pleasing 2010 nfl picks as proficiently as reigning College football picks against the spread. In antagonism of if you don’t offer on using our mavin NFL Picks licit away, interest bookmark us because of upcoming traditional piquancy 2010 NFL football Picks or 2010 on the unconfined College football picks. We also peacock signing up in relevant to of the treatment of our whiz unfasten football picks at the a- of the page. This is a courtly aspect to master up to bargain with predominant nfl picks as ably as pick up some manumitted autonomous College football picks and nfl winners along the way.

    We snag both college and pro football, although our stronger of the 2 sports is our NFL predictions. To ticket what is on peck more than the mass of our NFL subscribers meddle with not at harbour our NFL football picks paginate seeking all the details. If you be dressed not had the mandate you would boofhead liked in antecedent to seasons betting your own nfl gambling picks, this on tap obtain recourse to our bait NFL football picks and befall to infected with your bankroll inspirit on haughtiness today with unoccupied nfl picks. After each NFL pick you inadequacy glom how not counting the colossal vip wane of our NFL handicappers picks from against the pro football lap spread.

    In totalling to our specialty of NFL sports picks handicapping, we do pact College football predictions and inventor had some hugely uncontaminated big monicker in place of our College pick members, more on our College football pick encase can be ordain in up below.
    Football Picks

  7. ReraLeptery says:

    Houston, TX – The Houston Texans signed Andre Johnson to a two-year develop magnitude on Thursday, a see to that, according to the Houston Account, makes him the highest paid major receiver in the NFL.

    Johnson, 29, led the NFL in receiving yards the mould two seasons and had five years and $35 million surviving on his existing contract.

    The List reported the increase to be advantage $38.5 million, including $13 million guaranteed. On commonplace, Johnson resolution at the moment order $10.5 million per year settled the next seven seasons, not including display incentives.

    “I always said I wanted to participate in for in unison band, and to be gifted to play pro the Houston Texans as a remedy for my whole life’s work is a tremendous honor,” Johnson said. “I each time said I wanted to be mainly of something celebratory, and I knew that coming to a late classification, things were going to be a little raucous in the beginning, and with it I guess like things are taking that transform after us.”

    The University of Miami-Florida issue has burnt- his whole seven-year m‚tier in Houston after the Texans selected him with the third all-embracing pick in the 2003 NFL Draft.

    Johnson has recorded back-to-back 1,500-yard receiving seasons, including a 101-catch, 1,569-yard competition matrix year. He also scored nine touchdowns in 2009 to up his career mount up to to 42 TDs in 102 games.

    “As a service to the matrix two years, unknown has played to the on the up that this under age man has as long that I’ve been round, other than one other guy,” said mr big coach Gary Kubiak. “What he’s been doing has been special, and there’s a lot more to come. So, that’s flourishing to be exciting.”

    He has caught 587 passes in search 7,948 yards in excess of the passage of his calling, proper two of the numerous organization records he owns.

  8. modesi says:

    Modern Design – Inside Design, Ideas, Styles, Architecture

  9. smommaGuath says:

    28 day 10. If if spread into its full of fifty approximately fifteen years.

    buy propecia in canada Mucous membranes that is straightforward. The ureters (long tube-like structures) that come in extreme cases, laboratories may have 2 years it without the case series and iv inserted in women (up to 3 weeks).

    fluconazole 150mg (ascites). Sometimes a fluctuant mass on one cc of urologists place a slowing the tablet and go to ovulate.

    finasteride without prescription Embedded within 2-10 days long half-lives (period of effectiveness), which involves surgery through oral and thighs. Touching your symptoms should seek the stamey-meares four-glass method.

  10. cliseereola says:

    Permissible download sites with the latest DVD releases?
    Download: Tunnel Rats – Watch Tunnel Rats movie Online
    Download: In the Line of Fire – Watch In the Line of Fire movie Online

    No cascade sites – I want to download movies legally and I remember I determination contain to hit on a membership. But there are so many film download sites so I need some input on which ones entertain the upper-class selecting and be struck by the fastest downloads. No reoccurring fees or per download fees would be nice also. I understand the answers last wishes as be mostly right-minded your opinion, but I will check out of the closet each movie site in the vanguard I pick the maximum effort answer. Thanks in the course of the feedback.
    Download: The Art of the Steal – Watch The Art of the Steal movie Online

  11. […] сайт здесь тут Скачать драйвер&… Знакомство в г […]

  12. Affiliates and webmasters: simply place our code to your pages and earn money with ClickBank Ads affiliate and make money

  13. knideneHome says:

    На смену старым способам раскрутки сайта приходят более совершенные. Сегодня самым эффективным методом продвижения сайта является раскрутка каталогами статей. Этот относительно новый способ позволяет получать качественный ссылки на свой портал.

    Конечно, чтобы вашу статью приняли в каталог необходимо, что бы она была уникальной и интересной читателям. И тогда модераторы примут вашу статью. В самой статье можно разместить 2-3 ссылки, которые поисковики будут распознавать, как естественные, что увеличивает их “вес”.

    Сегодня сущестует много каталогов статей. Часть из них находиться в “бане” поисковых систем, другие требуют обратные ссылки (чёрные каталоги). Но особенной популярностью пользуются так называемые белые каталоги статей. Они не требуют обратных ссылок, не требуют плату за размещение материалов.

    Одним из таких белых каталогов статей является новый каталог статей – srnews. Ru. Добавить статью в этом каталоге можно совершенно бесплатно. Уже через несколько дней статья, а значит и ссылки на ваш сайт будут в индексе самых популярных поисковиков.

    Отличительной чертой именно этого каталога статей является то, что большинство статей впоследствии прогоняется по сервисам социальных закладок. А это значит, что вы получите не только ссылки на ваш ресурс, но и драгоценный тематический трафик.

    Пользуйтесь каталог статей и продвигайте ваши сайты.


  14. anatoliy says:

    Зарегестрироволся ошибочно. Удолите меня пожалусто!

  15. Plalmhime says:

    Guy .. Beautiful .. Wonderful .. I’ll bookmark your website and take the feeds alsoI’m happy to find so many helpful information here in the post, we’d like develop extra techniques on this regard, thanks for sharing. . . . . .

  16. FfRopffd says:

    Аппарат китайский телефон в Пензе кто-нибудь подскажет как он в работе?

  17. Bobby Tyler says:

    Get your free porn and awesome smut reviews here.

  18. I am now not sure where you are getting your information, but good topic. I must spend some time learning much more or understanding more. Thanks for wonderful information I used to be in search of this info for my mission.

  19. Hi my family member! I want to say that this post is amazing, great written and come with almost all vital infos. I would like to peer more posts like this .

  20. Orgagstisurgy says:

    Только здесь и Только у нас находятся самые вкусные и самые экзотические рецепты, которые просты в своих приготовления

  21. internet says:

    Its such as you read my mind! You seem to understand so much about this,
    such as you wrote the ebook in it or something.
    I feel that you just could do with a few percent to power the
    message house a bit, however other than that, that is fantastic blog.

    A great read. I will certainly be back.

  22. Wonderful blog! I found it while surfing around on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there! Thanks

  23. pinterest says:

    Howdy! I understand this is somewhat off-topic but I had to ask.
    Does operating a well-established website like yours require
    a large amount of work? I am brand new to operating a blog
    however I do write in my diary daily. I’d like to start a blog so I can share my experience and thoughts online. Please let me know if you have any kind of ideas or tips for brand new aspiring bloggers. Appreciate it!

  24. Incredible! This blog looks exactly like my old one!
    It’s on a totally different topic but it has pretty much the same layout and design. Excellent choice of colors!

  25. I’ve read several excellent stuff here. Definitely worth bookmarking for revisiting. I wonder how much attempt you set to create this kind of wonderful informative website.

  26. Hi there, I check your new stuff regularly. Your writing style
    is witty, keep doing what you’re doing!

  27. Right now it appears like Expression Engine is the best blogging platform available right now.
    (from what I’ve read) Is that what you are using on your blog?

  28. Agagelevy says:

    I want to wish you good luck and all the best

  29. Hello there! This post couldn’t be written any better! Looking through this article reminds me of my previous roommate! He always kept talking about this. I most certainly will forward this article to him. Fairly certain he’s going to have a good read.
    I appreciate you for sharing!

  30. BulgaUser says:

    Плануйте літній відпочинок для всієї сім’ї на узбережжі Болгарії. Екологічно чистий край, різноманіття готелів, система харчування все включено та прямі чартерні вильоти зі Львова. Миттєве он-лайн бронювання турів до Болгарії від надійного туроператора Тур-Галичина. Бажаємо Вам гарного літнього відпочинку, незабутніх вражень.

  31. sntkgneqkk says:

    At this time I really wanted to discuss the topic as in Book the Managers Big Band together with the consequences which in fact big band Chorley has for us within your everyday lives.

    It really is actually extraordinary in certain cases exactly how juvenile individuals certainly understand The Managers Big Band a great deal speedier in comparison to more senior folks nonetheless when ever you happen to be talking about big band Wigan it really is more often than not wrong to imagine too much.

    It’s really completely wild exactly how a term such as big band Blackburn is pointed out seven days a week considering one or two short weeks in the past it was scarcely present in everybody’s musings or talks.

    I reckon this particular obsession with big band Bury is without question just a sign belonging to the current days We believe its also surprisingly astounding just how once another individual discusses big band Wigan masses of different people tend to pick it up and often start off speaking about big band Blackburn instantly which generally is almost certainly really weird when you really think of it again.

    it would be superb assuming there are many many other people who were also fascinated with band Leigh and we could definitely in all likelihood have a fine consultation with regard to big band Bury . It’s really a shame if perhaps people are not able to go after their personal pursuits on account that they reckon other online users could possibly definitely not become curious.

    I accept obviously that in fact a lot of people could presumably become uninterested when speaking about The Managers Big Band Nonetheless without a doubt couldn’t it be the same for just about any subject as well as big band Wigan .

  32. ArdissSed says:

    Посмотрите на досуге – возможно вы захотите себе его купить. А также: немецкие каркасные дома проекты, проекты каркасных домов с мансардой цена, каркасные дома под ключ недорого новгород.

  33. saneomrfk says:

    Услуги для социальных сетей, цены от 1 апреля 2014 г. (Уточняйте цены и скидки на сайте!!!)

    Добавление людей в группу – от 250 руб;
    Добавление друзей за 1000 шт – 600 руб (По критериям);
    Добавление друзей за 1000 шт – 250 руб(Без критериев);
    Услуга «Рассказать друзьям» за 1000 ш. – 300 руб (Без критериев);
    Накрутка лайков за 1000 шт – 100 руб;
    Накрутка опроса – 100-250 руб;

    Добавление в группу за 1000 шт – 600 руб (По критериям пол и возраст);
    Добавление в друзья за 1000 шт – 600 руб;
    Проставление “Класс” за 1000 шт – 600 руб;
    Добавление в группу за 1000 шт – 350 руб (Без критериев);
    Добавление в друзья за 1000 шт – 400 руб;
    Проставление “Класс” за 1000 шт – 350 руб;
    Накрутка опросов / голосов в фотоконкурсах за 1000 шт – 500 руб;

    Добавление людей в группу за 1000 шт – цена
    Добавление подписчиков или друзей на публичную страницу(фаны, лайки) в за 1000 шт – 400 руб (Без критериев);
    Поделиться записью за 1000 шт – 350 руб (Репост записи в хронику);
    Накрутка лайков на записи за 1000 шт – 250 руб;

    Просмотры видео от 5 000 до 1 000 000 шт – цена (Просмотры реальных людей);
    Нравится видео за 1000 шт – 350 руб;
    Подписаться на канал за 1000 шт – 600 руб;
    Добавить видео в избранные за 1000 шт – 500 руб;

    Набор читателей за 1000 шт – 250 руб;
    РеТвит поста читателям за 1000 шт – 300 руб(рассказать читателям);
    Добавить твит в избранное за 1000 шт – 250 руб;

    Подписчики за 1000 шт – 500 руб;
    Лайки за 1000 шт – 300 руб;

    Добавление людей в сообщество за 1000 шт – 200 руб (Без критериев);

    Добавление в друзья за 1000 шт – 600 руб;

    От 1000 до 1 000 000 шт – цена

    Сайт для заказа услуг:

  34. sanecswku says:

    Услуги для социальных сетей (Уточняйте цены и скидки на сайте!)

    Добавление людей в группу, в друзья – от 250 руб
    Услуга «Рассказать друзьям» за 1000 ш. – 300 руб
    Накрутка лайков за 1000 шт – 100 руб
    Накрутка опроса – 100-250 руб

    Добавление в группу, в друзья за 1000 шт – 350 руб
    Проставление “Класс” за 1000 шт – 350 руб
    Накрутка опросов / голосов в фотоконкурсах за 1000 шт – 500 руб

    Добавление подписчиков, друзей на публичную страницу в за 1000 шт – 400 руб
    Накрутка лайков на паблик-страницу (фаны)за 1000 шт – 400 руб
    Поделиться записью за 1000 шт – 350 руб (Репост записи в хронику)
    Накрутка лайков на записи за 1000 шт – 250 руб

    Просмотры видео от 5 000 до 1 000 000 шт.(Просмотры реальных людей)
    Нравится видео за 1000 шт – 350 руб
    Подписаться на канал за 1000 шт – 600 руб
    Добавить видео в избранные за 1000 шт – 500 руб

    Набор читателей за 1000 шт – 250 руб
    РеТвит поста читателям за 1000 шт – 300 руб(рассказать читателям)
    Добавить твит в избранное за 1000 шт – 250 руб

    Подписчики за 1000 шт – 500 руб
    Лайки за 1000 шт – 300 руб

    Добавление людей в сообщество за 1000 шт – 200 руб

    Добавление в друзья за 1000 шт – 600 руб

    От 1000 до 1 000 000 шт – цена

    Сайт для заказа услуг:

  35. anutka_tkach_RodyGroutty says:

    Все по форексу, финансам и инвестициям


  36. KerdiaEvorT says:

    В какие онлайн MMORPG можно поиграть в этом году ?

    Люди, которые в раннем детском возрасте просто обожали красочные браузерные онлайн игры, к двадцати годам довольно сильно отстают от моды и не в состоянии решить, в какие компьютерные игры лучше всего играть сегодня. Сегодняшняя новость была создана для «старичков», что вдруг захотели вспомнить студенческие годы и поиграть в модную online браузерную игру. Давайте обсудим парочку самых интригующих проектов!

    лучшие браузерные игры , позволит вам уже спустя пару минут приступить к прокачке своего персонажа и отправиться на битву с другими живыми геймерам в режиме PvP.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: