MutexCreate
 
Creates a mutex used for synchronizing the execution of threads

Syntax

Declare Function MutexCreate ( ) As Any Ptr

Usage

result = MutexCreate

Return Value

The Any Ptr handle of the mutex created, or the null pointer (0) on failure.

Description

Mutexes, short for "Mutually Exclusive", are a way of synchronizing shared data within threads. If there is a global variable used by multiple threads (or a local variable used by a single thread, called multiple times), it should be "locked" during its use with a mutex. This halts all threads using MutexLock with that mutex, until it is unlocked with MutexUnlock.

Mutexcreate creates a mutex, returning a handle which is to be referred to when locking, unlocking, or destroying the mutex. Mutexes created with Mutexcreate should be destroyed when no longer needed or before the end of the program with MutexDestroy.

A mutex is a lock that guarantees three things:
1. Atomicity - Locking a mutex is an atomic operation, meaning that the operating system (or threads library) assures you that if you locked a mutex, no other thread succeeded in locking this mutex at the same time.
2. Singularity - If a thread managed to lock a mutex, it is assured that no other thread will be able to lock the thread until the original thread releases the lock.
3. Non-Busy Wait - If a thread attempts to lock a thread that was locked by a second thread, the first thread will be suspended (and will not consume any CPU resources) until the lock is freed by the second thread. At this time, the first thread will wake up and continue execution, having the mutex locked by it.

Example

'' Threading syncronyzation using Mutexes
'' If you comment out the lines containing "MutexLock" and "MutexUnlock",
'' the threads will not be in sync and some of the data may be printed
'' out of place.

Const MAX_THREADS = 10

Declare Sub thread( ByVal id_ptr As Any Ptr )
Declare Sub teletype (ByVal text As String, ByVal x As Integer, ByVal y As Integer)

Dim Shared threadsync As Any Ptr

Dim i As Integer

Dim handleTb(0 To MAX_THREADS-1) As Any Ptr

'' Create a mutex to syncronize the threads
threadsync = MutexCreate

'' Create threads
For i = 0 To MAX_THREADS-1
    handleTb(i) = ThreadCreate(@thread, @i)
    If handleTb(i) = 0 Then
        Print "Error creating thread:"; i
        Exit For
    End If
Next

'' Wait until all threads are finished
For i = 0 To MAX_THREADS-1
    If( handleTb(i) <> 0 ) Then
        ThreadWait( handleTb(i) )
    End If
Next

teletype "Testing.................", 1, 1
teletype "Testing again...........", 10, 1

'' Discard the mutex when we are through using teletype
MutexDestroy threadsync

Sub thread( ByVal id_ptr As Any Ptr )
    Dim id As Integer
    id = *Cast( Integer Ptr, id_ptr )
    teletype "Thread (" & id & ").........", 1, 1+id
End Sub

'' Teletype unfurls some text across the screen at a given location
Sub teletype (ByVal text As String, ByVal x As Integer, ByVal y As Integer)
    Dim i As Integer

    For i = 0 To Len(text)-1
        '' MutexLock prevents the two simultaneously running
        '' threads from sharing "x", "y", and "a"
        MutexLock threadsync

        Locate y, x+i
        Print Chr(text[i])

        '' MutexUnlock releases these variables for other use
        MutexUnlock threadsync

        Sleep 25
   Next
End Sub


Dialect Differences

  • Threading is not allowed in the -lang qb dialect.

Platform Differences

  • The DOS version of FreeBASIC does not allow for threads, as the OS does not support them.
  • In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue.

Differences from QB

  • New to FreeBASIC

See also

Сайт ПДСНПСР. Если ты патриот России - жми сюда!


Знаете ли Вы, как разрешается парадокс Ольберса?
(Фотометрический парадокс, парадокс Ольберса - это один из парадоксов космологии, заключающийся в том, что во Вселенной, равномерно заполненной звёздами, яркость неба (в том числе ночного) должна быть примерно равна яркости солнечного диска. Это должно иметь место потому, что по любому направлению неба луч зрения рано или поздно упрется в поверхность звезды.
Иными словами парадос Ольберса заключается в том, что если Вселенная бесконечна, то черного неба мы не увидим, так как излучение дальних звезд будет суммироваться с излучением ближних, и небо должно иметь среднюю температуру фотосфер звезд. При поглощении света межзвездным веществом, оно будет разогреваться до температуры звездных фотосфер и излучать также ярко, как звезды. Однако в дело вступает явление "усталости света", открытое Эдвином Хабблом, который показал, что чем дальше от нас расположена галактика, тем больше становится красным свет ее излучения, то есть фотоны как бы "устают", отдают свою энергию межзвездной среде. На очень больших расстояниях галактики видны только в радиодиапазоне, так как их свет вовсе потерял энергию идя через бескрайние просторы Вселенной. Подробнее читайте в FAQ по эфирной физике.

НОВОСТИ ФОРУМАФорум Рыцари теории эфира
Рыцари теории эфира
 10.11.2021 - 12:37: ПЕРСОНАЛИИ - Personalias -> WHO IS WHO - КТО ЕСТЬ КТО - Карим_Хайдаров.
10.11.2021 - 12:36: СОВЕСТЬ - Conscience -> РАСЧЕЛОВЕЧИВАНИЕ ЧЕЛОВЕКА. КОМУ ЭТО НАДО? - Карим_Хайдаров.
10.11.2021 - 12:36: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от д.м.н. Александра Алексеевича Редько - Карим_Хайдаров.
10.11.2021 - 12:35: ЭКОЛОГИЯ - Ecology -> Биологическая безопасность населения - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> Проблема государственного терроризма - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> ПРАВОСУДИЯ.НЕТ - Карим_Хайдаров.
10.11.2021 - 12:34: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вадима Глогера, США - Карим_Хайдаров.
10.11.2021 - 09:18: НОВЫЕ ТЕХНОЛОГИИ - New Technologies -> Волновая генетика Петра Гаряева, 5G-контроль и управление - Карим_Хайдаров.
10.11.2021 - 09:18: ЭКОЛОГИЯ - Ecology -> ЭКОЛОГИЯ ДЛЯ ВСЕХ - Карим_Хайдаров.
10.11.2021 - 09:16: ЭКОЛОГИЯ - Ecology -> ПРОБЛЕМЫ МЕДИЦИНЫ - Карим_Хайдаров.
10.11.2021 - 09:15: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Екатерины Коваленко - Карим_Хайдаров.
10.11.2021 - 09:13: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вильгельма Варкентина - Карим_Хайдаров.
Bourabai Research Institution home page

Боровское исследовательское учреждение - Bourabai Research Bourabai Research Institution