Nim counting over multiple threads

Viewed 674

I'm currently trying to count how many times I requested a website. In python I would just use a global variable but I have no idea how I would write this in nim.

import httpclient

proc threadMain(a: int) {.thread.} =

    var client = newHttpClient()
    while true:
      try:
        var r = client.getContent("URL")
        echo "sent"
        #Count here
      except:
        echo "error"

var thread: array[0..10, Thread[int]]

for i in 0..10:
  thread[i].createThread(threadMain, i)

thread.joinThreads()
1 Answers

This is explained almost as a copy in the "Nim in Action" book, page 174.

First of all, if you used a global in Python, you had to use a lock or risk a race condition. The thing is not different in Nim: first create a global, and guard it using a lock.

import locks

var counterLock: Lock
initLock(counterLock)
var counter {.guard: counterLock.} = 0

Now use a withLock where you need to update the counter:

withLock counterLock:
  counter.inc

The chapter of the book related to paralellism/concurrency is very good. You should check it, as it also explains concurrency (your code is an example of concurrency being better than threading) or how to use Channels to pass data between threads, for example.

Related