Skip to content

Instantly share code, notes, and snippets.

@rayman22201
Forked from iffy/sharedlistprobs.nim
Last active October 5, 2019 03:23
Show Gist options
  • Save rayman22201/a3c136f20ff6b610bb5caeaae0390990 to your computer and use it in GitHub Desktop.
Save rayman22201/a3c136f20ff6b610bb5caeaae0390990 to your computer and use it in GitHub Desktop.
SharedList appears empty in second thread, but full in main thread
import logging
import os
import sharedlist
type
FunctionLogger = ref object of Logger
LogFunc = proc(msg:cstring) {.raises: [Exception], gcsafe, tags: [TimeEffect, WriteIOEffect, ReadIOEffect].}
var LOG_FUNCTIONS: ptr SharedList[LogFunc]
var logger {.threadvar.} : FunctionLogger
proc init_log_list*() =
## call this first to setup the global Log list
LOG_FUNCTIONS = cast[ptr SharedList[LogFunc]](allocShared0(sizeof(SharedList[LogFunc])))
LOG_FUNCTIONS[].init()
proc destroy_log_list*() =
deinitSharedList(LOG_FUNCTIONS[])
deallocShared(LOG_FUNCTIONS)
proc init_logging*() =
## Set up logging if it isn't already set up
## Must be called once per thread if you want logging
if logger.isNil:
new(logger)
addHandler(logger)
method log*(logger: FunctionLogger, level: Level, args: varargs[string, `$`]) {.gcsafe.} =
#echo "log: ", $getCurrentProcessId(), ".", $getThreadId(), " ", $args
echo "logger.isNil: ", $logger.isNil()
if level >= logger.levelThreshold:
echo "in threshold"
let ln = substituteLog(logger.fmtStr, level, args)
for fn in LOG_FUNCTIONS[]:
echo "LOG_FUNCTION yes"
fn(ln)
proc register_logger*(fn:LogFunc) =
## Register a function to receive logging events from Nim.
## The function will be called with strings to be logged.
#echo "adding log function to LOG_FUNCTIONS ", $getCurrentProcessId(), ".", $getThreadId()
LOG_FUNCTIONS[].add(fn)
@rayman22201
Copy link
Author

Call init_log_list() before you start any threads.
Remember to call destroy_log_list() on program exit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment