MutexLock
 
Acquires a mutex

Syntax

Declare Sub MutexLock ( ByVal id As Any Ptr )

Usage

MutexLock( id )

Parameters

id
The Any Ptr handle of the mutex to be locked.

Description

Mutexlock halts any other threads using a mutex "handle", generated by MutexCreate, until the handle is unlocked with MutexUnlock.

See MutexCreate for more general information on mutexes.

Example

'' Threading synchronization 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.

Declare Sub thread1( param As Any Ptr )
Declare Sub thread2( param 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 Shared thread1handle As Any Ptr
Dim Shared thread2handle As Any Ptr

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

'' Call thread 1
thread1handle = ThreadCreate(@thread1)
If thread1handle = 0 Then
    Print "Error creating thread1"
End If

'' Call thread 2
thread2handle = ThreadCreate(@thread2)
If thread2handle = 0 Then
    Print "Error creating thread1"
End If

'' Wait until both threads are finished
ThreadWait(thread1handle)
ThreadWait(thread2handle)

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

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

Sleep
End

'' Thread 1 calls a simple "teletype" routine
Sub thread1( param As Any Ptr )
    teletype "This is a test...", 4, 1
End Sub

'' ...As does thread 2
Sub thread2( param As Any Ptr )
    teletype "This is another test...", 7, 1
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, a As Integer
    Dim text_length As Integer

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

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

        '' MutexUnlock releases these variables for other use
        MutexUnlock threadsync

        Sleep 25
   Next a
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

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


Знаете ли Вы, в чем фокус эксперимента Майкельсона?

Эксперимент А. Майкельсона, Майкельсона - Морли - действительно является цирковым фокусом, загипнотизировавшим физиков на 120 лет.

Дело в том, что в его постановке и выводах произведена подмена, аналогичная подмене в школьной шуточной задачке на сообразительность, в которой спрашивается:
- Cколько яблок на березе, если на одной ветке их 5, на другой ветке - 10 и так далее
При этом внимание учеников намеренно отвлекается от того основополагающего факта, что на березе яблоки не растут, в принципе.

В эксперименте Майкельсона ставится вопрос о движении эфира относительно покоящегося в лабораторной системе интерферометра. Однако, если мы ищем эфир, как базовую материю, из которой состоит всё вещество интерферометра, лаборатории, да и Земли в целом, то, естественно, эфир тоже будет неподвижен, так как земное вещество есть всего навсего определенным образом структурированный эфир, и никак не может двигаться относительно самого себя.

Удивительно, что этот цирковой трюк овладел на 120 лет умами физиков на полном серьезе, хотя его прототипы есть в сказках-небылицах всех народов всех времен, включая барона Мюнхаузена, вытащившего себя за волосы из болота, и призванных показать детям возможные жульничества и тем защитить их во взрослой жизни. Подробнее читайте в 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