Blog · November 2026 · 7 min read Blog · Novembre 2026 · 7 min de lectureالمدونة · نوفمبر 2026 · 7 دقائق قراءة

The bug my thread animation never showed Le bug que mon animation de threads ne montrait pasالخطأ الذي لم تُظهره رسومي المتحركة عن الخيوط

I built an animation to explain threads and semaphores. It showed perfectly how to use a lock, and never why you need one. So I ran the experiment in C: two threads, one counter, and up to 860,000 lost updates. J'ai construit une animation pour expliquer les threads et les sémaphores. Elle montrait parfaitement comment utiliser un verrou, mais jamais pourquoi on en a besoin. Alors j'ai fait l'expérience en C : deux threads, un compteur, et jusqu'à 860 000 mises à jour perdues.بنيت رسوماً متحركة لشرح الخيوط والإشارات (semaphores). كانت تُظهر بإتقان كيف نستعمل القفل، لكنها لم تُظهر أبداً لماذا نحتاج إليه. فأجريت التجربة بلغة C: خيطان، وعدّاد واحد، وما يصل إلى 860,000 تحديث ضائع.

The projectLe projetالمشروع

The Threads and Semaphores Visualizer is a single HTML file with no dependencies. One tab follows pthread_create() and pthread_join() on two timelines. Another shows two threads competing for a critical section: the semaphore goes from 1 to 0, the second thread blocks, then gets in when the first calls sem_post(). Below the animation, a beginner's guide explains each function with C examples. Le Threads and Semaphores Visualizer est un seul fichier HTML, sans dépendance. Un onglet suit pthread_create() et pthread_join() sur deux lignes de temps. Un autre montre deux threads qui se disputent une section critique : le sémaphore passe de 1 à 0, le second thread se bloque, puis entre quand le premier appelle sem_post(). Sous l'animation, un guide pour débutants explique chaque fonction avec des exemples en C.Threads and Semaphores Visualizer ملف HTML واحد بلا أي تبعيات. يتتبّع أحد التبويبات pthread_create() وpthread_join() على خطّين زمنيين. ويُظهر تبويب آخر خيطين يتنافسان على قسم حرج: تنتقل الإشارة من 1 إلى 0، فيُحجب الخيط الثاني، ثم يدخل عندما يستدعي الأول sem_post(). وتحت الرسوم، دليل للمبتدئين يشرح كل دالة بأمثلة بلغة C.

Rereading it, I noticed what was missing. Every step showed the lock working. Nothing showed what happens without it, which is the only reason locks exist. A student could follow the whole animation and still think the semaphore is a formality. En la relisant, j'ai vu ce qui manquait. Chaque étape montrait le verrou qui fonctionne. Rien ne montrait ce qui se passe sans lui, alors que c'est la seule raison d'exister des verrous. Un étudiant pouvait suivre toute l'animation et penser encore que le sémaphore est une formalité.عند إعادة قراءتها، لاحظت ما كان ناقصاً. كل خطوة كانت تُظهر القفل وهو يعمل. ولا شيء يُظهر ما يحدث من دونه، مع أنه السبب الوحيد لوجود الأقفال. كان بإمكان طالب أن يتابع الرسوم كلها ويظل يظن أن الإشارة مجرد إجراء شكلي.

The experimentL'expérienceالتجربة

Two threads add 1 to the same global counter, one million times each. The answer should be 2,000,000. Deux threads ajoutent 1 au même compteur global, un million de fois chacun. Le résultat devrait être 2 000 000.خيطان يضيفان 1 إلى العدّاد العام نفسه، مليون مرة لكل منهما. يجب أن تكون النتيجة 2,000,000.

long counter = 0;

void* work(void* arg) {
    for (int i = 0; i < 1000000; i++)
        counter++;
    return NULL;
}
// main: pthread_create twice, pthread_join twice, print counter

Five runs on my laptop, compiled with gcc: Cinq exécutions sur mon ordinateur, compilé avec gcc :خمس عمليات تشغيل على حاسوبي، بعد الترجمة بـ gcc:

RunExécutionالتشغيلcounterLostPerduesالضائعة
11,630,462369,538
21,138,389861,611
31,823,311176,689
41,433,699566,301
51,343,202656,798

Never the right answer, and never the same wrong answer twice. In the worst run, 43% of the additions disappeared. No crash, no warning: just a wrong number. Jamais le bon résultat, et jamais deux fois le même mauvais résultat. Dans la pire exécution, 43 % des additions ont disparu. Pas de plantage, pas d'avertissement : juste un nombre faux.لم تظهر النتيجة الصحيحة أبداً، ولم تتكرر النتيجة الخاطئة نفسها مرتين. في أسوأ تشغيل، اختفت 43% من عمليات الإضافة. لا انهيار ولا تحذير: مجرد رقم خاطئ.

Why counter++ loses updatesPourquoi counter++ perd des mises à jourلماذا يُضيّع counter++ التحديثات

counter++ looks like one operation, but the processor does it in three: load the value into a register, add 1, store it back. Each thread has its own registers. If the two threads interleave like this, two increments produce only one: counter++ ressemble à une seule opération, mais le processeur la fait en trois : charger la valeur dans un registre, ajouter 1, la réécrire. Chaque thread a ses propres registres. Si les deux threads s'entrelacent comme ceci, deux incréments n'en donnent qu'un seul :يبدو counter++ عملية واحدة، لكن المعالج ينفّذه في ثلاث: تحميل القيمة في سجلّ، ثم إضافة 1، ثم كتابتها من جديد. ولكل خيط سجلاته الخاصة. فإذا تداخل الخيطان على هذا النحو، أنتجت زيادتان زيادة واحدة فقط:

Thread 1Thread 1الخيط 1Thread 2Thread 2الخيط 2counter
load → 55
load → 55
add → 65
add → 65
store 66
store 66

Thread 2 read the value before thread 1 wrote its result, then overwrote it. This is a race condition: the result depends on the order in which the threads happen to run. That is also why it is so hard to catch. With small loops the threads rarely overlap, so the program can pass every test and fail later in production. Le thread 2 a lu la valeur avant que le thread 1 écrive son résultat, puis l'a écrasé. C'est une race condition (situation de compétition) : le résultat dépend de l'ordre dans lequel les threads s'exécutent par hasard. C'est aussi pour ça qu'elle est si difficile à attraper. Avec de petites boucles, les threads se chevauchent rarement : le programme peut passer tous les tests et échouer plus tard en production.قرأ الخيط 2 القيمة قبل أن يكتب الخيط 1 نتيجته، ثم كتب فوقها. هذا ما يسمى حالة السباق، أو race condition: تتوقف النتيجة على الترتيب الذي يصادف أن تعمل به الخيوط. ولهذا أيضاً يصعب اكتشافها: مع الحلقات الصغيرة نادراً ما تتداخل الخيوط، فقد ينجح البرنامج في كل الاختبارات ثم يفشل لاحقاً في الإنتاج.

The fix, and its priceLa correction, et son prixالحل، وثمنه

Wrapping counter++ in sem_wait() and sem_post() gave 2,000,000 every time. But I also timed it: Entourer counter++ de sem_wait() et sem_post() a donné 2 000 000 à chaque fois. Mais j'ai aussi mesuré le temps :إحاطة counter++ بـ sem_wait() وsem_post() أعطت 2,000,000 في كل مرة. لكنني قست الزمن أيضاً:

VersionVersionالنسخةResultRésultatالنتيجةTimeTempsالزمن
No lockSans verrouبلا قفلwrongfauxخاطئة~55 ms
Semaphore around each counter++Sémaphore autour de chaque counter++إشارة حول كل counter++2,000,000~5.9 s
Atomic increment (atomic_fetch_add)Incrément atomique (atomic_fetch_add)زيادة ذرّية (atomic_fetch_add)2,000,000~65 ms
Count locally, add once under the semaphoreCompter en local, ajouter une fois sous le sémaphoreالعدّ محلياً، ثم الإضافة مرة واحدة تحت الإشارة2,000,000~50 ms

Correct, but about 100 times slower: taking and releasing the semaphore two million times costs far more than the addition it protects, and the two threads spend their time waiting for each other. Two better options. For a single counter, an atomic increment does the load, add and store as one indivisible operation. In general, the best lock is the one you do not take: each thread counts in a local variable, and only the final result goes through the critical section, once per thread. Correct, mais environ 100 fois plus lent : prendre et rendre le sémaphore deux millions de fois coûte bien plus que l'addition qu'il protège, et les deux threads passent leur temps à s'attendre. Deux meilleures options. Pour un simple compteur, un incrément atomique fait le chargement, l'addition et l'écriture en une seule opération indivisible. En général, le meilleur verrou est celui qu'on ne prend pas : chaque thread compte dans une variable locale, et seul le résultat final passe par la section critique, une fois par thread.صحيح، لكنه أبطأ بنحو 100 مرة: أخذ الإشارة وتحريرها مليوني مرة يكلّف أكثر بكثير من عملية الإضافة التي تحميها، ويقضي الخيطان وقتهما في انتظار أحدهما الآخر. وهناك خياران أفضل. لعدّاد بسيط، تنفّذ الزيادة الذرّية التحميل والإضافة والكتابة كعملية واحدة لا تتجزأ. وعموماً، أفضل قفل هو الذي لا تأخذه: يعدّ كل خيط في متغير محلي، ولا تمر عبر القسم الحرج إلا النتيجة النهائية، مرة واحدة لكل خيط.

What else the animation simplifiedCe que l'animation simplifiait encoreما الذي بسّطته الرسوم أيضاً

  • Who goes next is not guaranteed. The animation showed thread 2 entering right after sem_post(), as if waiting threads formed a queue. POSIX only promises that one waiting thread is allowed to continue; which one, and whether another thread grabs the semaphore first, is not specified.Qui passe ensuite n'est pas garanti. L'animation montrait le thread 2 qui entre juste après sem_post(), comme si les threads en attente formaient une file. POSIX promet seulement qu'un thread en attente peut continuer ; lequel, et si un autre thread prend le sémaphore avant lui, ce n'est pas précisé.من يدخل بعد ذلك ليس مضموناً. كانت الرسوم تُظهر الخيط 2 يدخل مباشرة بعد sem_post()، وكأن الخيوط المنتظرة تقف في طابور. لا يَعِد POSIX إلا بأن خيطاً منتظراً واحداً يُسمح له بالمتابعة؛ أما أيّها، وهل يسبقه خيط آخر إلى الإشارة، فغير محدد.
  • A semaphore at 1 is not quite a mutex. A mutex has an owner: only the thread that locked it can unlock it. Any thread can post a semaphore, which is exactly what makes semaphores useful for signalling between threads, and a mutex the usual choice for a simple lock.Un sémaphore à 1 n'est pas tout à fait un mutex. Un mutex a un propriétaire : seul le thread qui l'a verrouillé peut le déverrouiller. N'importe quel thread peut faire sem_post() sur un sémaphore, et c'est justement ce qui rend les sémaphores utiles pour se signaler des choses entre threads, et le mutex le choix habituel pour un simple verrou.الإشارة بقيمة 1 ليست تماماً كائن mutex. للـ mutex مالك: فقط الخيط الذي قفله يستطيع فتحه. أما الإشارة فيستطيع أي خيط استدعاء sem_post() عليها، وهذا بالضبط ما يجعل الإشارات مفيدة لتبادل الإشعارات بين الخيوط، ويجعل الـ mutex الخيار المعتاد للقفل البسيط.
  • Portability. The guide said POSIX threads need WSL on Windows; the MinGW-w64 gcc that ships with Code::Blocks compiled every example above. And it did not mention macOS, where sem_init() is not supported: you need named semaphores (sem_open()) or dispatch_semaphore_t.La portabilité. Le guide disait que les threads POSIX demandent WSL sous Windows ; le gcc MinGW-w64 fourni avec Code::Blocks a compilé tous les exemples ci-dessus. Et il ne parlait pas de macOS, où sem_init() n'est pas supporté : il faut des sémaphores nommés (sem_open()) ou dispatch_semaphore_t.قابلية النقل. كان الدليل يقول إن خيوط POSIX تحتاج إلى WSL على ويندوز؛ لكن مترجم gcc من MinGW-w64 المرفق مع Code::Blocks ترجم كل الأمثلة أعلاه. ولم يكن يذكر macOS، حيث sem_init() غير مدعومة: يلزم استعمال الإشارات المسمّاة (sem_open()) أو dispatch_semaphore_t.

And one plain bug: the JavaScript gave the thread in the critical section the class in_critical, while the CSS styled in-critical. One character apart, so the card that was supposed to light up never did. Et un bug tout simple : le JavaScript donnait au thread en section critique la classe in_critical, alors que le CSS stylait in-critical. Un seul caractère d'écart, donc la carte censée s'allumer ne s'allumait jamais.وخطأ بسيط أيضاً: كانت شيفرة JavaScript تعطي الخيط الموجود في القسم الحرج الصنف in_critical، بينما كان CSS يُنسّق in-critical. فرق حرف واحد، فلم تُضئ البطاقة التي كان يُفترض أن تُضيء أبداً.

What I changedCe que j'ai changéما الذي غيّرته

  • A new Race condition tab that plays the interleaving above step by step, with each thread's register and the shared counter, until one update is lost.Un nouvel onglet Race condition qui rejoue pas à pas l'entrelacement ci-dessus, avec le registre de chaque thread et le compteur partagé, jusqu'à la mise à jour perdue.تبويب جديد Race condition يعيد عرض التداخل أعلاه خطوة بخطوة، مع سجل كل خيط والعدّاد المشترك، حتى ضياع التحديث.
  • The experiment and the timing table in the guide, plus the corrected notes on wake-up order, mutexes, Windows and macOS.L'expérience et le tableau des temps dans le guide, avec les remarques corrigées sur l'ordre de réveil, les mutex, Windows et macOS.التجربة وجدول الأزمنة في الدليل، مع الملاحظات المصححة حول ترتيب الاستيقاظ، والـ mutex، وويندوز وmacOS.
  • The CSS class fix, Play restarting from the beginning when pressed on the last step, and step descriptions announced to screen readers.La correction de la classe CSS, le bouton Play qui recommence depuis le début quand on l'appuie à la dernière étape, et les descriptions d'étapes annoncées aux lecteurs d'écran.تصحيح صنف CSS، وزر Play الذي يبدأ من جديد عند الضغط عليه في الخطوة الأخيرة، وإعلان وصف الخطوات لقارئات الشاشة.

TakeawaysÀ retenirالخلاصة

  • To teach a fix, show the bug first. A lock only makes sense once you have seen a number go wrong.Pour enseigner une correction, montrer d'abord le bug. Un verrou n'a de sens qu'après avoir vu un nombre devenir faux.لتعليم حلّ ما، أظهر الخطأ أولاً. فالقفل لا يكتسب معناه إلا بعد أن ترى رقماً يصبح خاطئاً.
  • A single line of code can be several machine steps. Shared data needs a lock or an atomic operation.Une seule ligne de code peut correspondre à plusieurs étapes machine. Une donnée partagée a besoin d'un verrou ou d'une opération atomique.سطر واحد من الشيفرة قد يعني عدة خطوات للآلة. والبيانات المشتركة تحتاج إلى قفل أو عملية ذرّية.
  • Correct is not enough: measure. Lock as little and as rarely as possible.Correct ne suffit pas : il faut mesurer. Verrouiller le moins possible, et le moins souvent possible.الصحة وحدها لا تكفي: يجب القياس. اقفل بأقل قدر ممكن، وبأقل تكرار ممكن.
  • Race conditions do not crash, they lie. Test concurrent code with many iterations, and run it several times.Les race conditions ne plantent pas, elles mentent. Tester le code concurrent avec beaucoup d'itérations, et le lancer plusieurs fois.حالات السباق لا تتسبب في الانهيار، بل تكذب. اختبر الشيفرة المتزامنة بعدد كبير من التكرارات، وشغّلها عدة مرات.

Try the animation, or read the code and the guide on GitHub. Essayez l'animation, ou lisez le code et le guide sur GitHub.جرّب الرسوم المتحركة، أو اقرأ الشيفرة والدليل على GitHub.