How to use Mutexes

General FreeBASIC programming questions.
Post Reply
mrminecrafttnt
Posts: 131
Joined: Feb 11, 2013 12:23

How to use Mutexes

Post by mrminecrafttnt »

How did i use mutexes to fix this glitches?
Createmutex is already implemented..

Code: Select all

type threaddata
    char as ubyte
    p as ubyte
    Mutexdata as any ptr
end type


sub printchar(c as any ptr)
    dim as threaddata ptr mythreaddataptr = c
    dim as threaddata td = *mythreaddataptr
    
    static p as integer
    p+=1
    
    for i as integer = 1 to 90
        locate td.p,i
        print chr(td.char);
        sleep 1
    next
    
end sub

sub threadbuilder
    dim as any ptr thread(0 to 256)
    dim as integer threadid
    dim as threaddata pd
    dim as threaddata ptr pdadr = @pd
    dim as any ptr td = pdadr
    for i as ubyte = asc("A") to asc("A")+25
        with pd
            .char = i
            .p=threadid+1
            .Mutexdata =  MUTEXCREATE ' How to use this?
        end with
        
        thread(threadid)=ThreadCreate (@printchar,pdadr)
        threadid +=1
        sleep 1
    next
    dim as integer threadidend = threadid
    for i as ubyte = 0 to threadidend-1
        threadwait(thread(threadid))
    next
end sub

threadbuilder
sleep
fxm
Moderator
Posts: 12081
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: How to use Mutexes

Post by fxm »

You must have a threaddata instance for each thread (no assumptions can be made about the order in which multiple create threads actually start executing), and a common mutex for all threads (to impose mutual exclusion on the two instructions 'locate' + 'print').

Example with 20 lines and 70 columns:

Code: Select all

type threaddata
    char as ubyte
    p as ubyte
    static Mutexdata as any ptr
end type

dim as any ptr threaddata.Mutexdata

sub printchar(byval c as any ptr)
    dim as threaddata ptr mythreaddataptr = c
    
    for i as integer = 1 to 70
        MutexLock(mythreaddataptr->Mutexdata)
        locate mythreaddataptr->p,i
        print chr(mythreaddataptr->char);
        MutexUnlock(mythreaddataptr->Mutexdata)
        sleep 1
    next
    
end sub

sub threadbuilder
    dim as threaddata pd(0 to 19)
    dim as any ptr thread(0 to 19)
    threaddata.Mutexdata = MutexCreate
    for i as ubyte = 0 to 19
        with pd(i)
            .char = asc("A") + i
            .p=i + 1
        end with
        
        thread(i)=ThreadCreate (@printchar,@pd(i))
        sleep 1
    next
    for i as ubyte = 0 to 19
        threadwait(thread(i))
    next
    MutexDestroy(threaddata.Mutexdata)
    print
end sub

threadbuilder

sleep
fxm
Moderator
Posts: 12081
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: How to use Mutexes

Post by fxm »

If you are interested in the topic, in addition to the keyword pages, I wrote a 6 article 'Multi-Threading' section in the Programmer's Guide.
Post Reply