Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 181
  • Last Modified:

Locking Functions due to Multi-Threading in Visual Basic 6 Possible?

Is theere a way to lock a function (or rather, a selection of code) from being executed by more than 1 thread.  I noticed there was a SyncLock command in VB .NET but this does not exist for VB6.  Can someone give me the deatails so i can implement the same kind of feature.
If it is of importance i am calling a function that writes out to a file.  The problem is that there are many threads running that could call this same function to write out to the file (append to it).  Since i could actually be writing to the file before i am interrupted by another thread which causes it to begin writing you can see it can end up being a mess without the lock feature

1 Solution
how about CreateMutex or Semaphore you can create a "Lock" on a thread untill the process ended.

Declare Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (lpMutexAttributes As SECURITY_ATTRIBUTES, ByVal bInitialOwner As Long, ByVal lpName As String) As Long

Private Declare Function ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Sub Form_Load()
    Dim hMutex As Long
    'Try to create a new Mutex
    hMutex = CreateMutex(ByVal 0&, 1, App.Title)
    'Did the mutex already exist?
    If (Err.LastDllError = ERROR_ALREADY_EXISTS) Then

        'Then Dont write to the file.-----

        ReleaseMutex hMutex
        CloseHandle hMutex
          exit sub
        Write to the File
    End If
End Sub

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now