summaryrefslogtreecommitdiff
path: root/rts/ThreadLabels.c
blob: 5b3362a2b8e3281a9886a0c7f11eec4071d3e1ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* -----------------------------------------------------------------------------
 * ThreadLabels.c
 *
 * (c) The GHC Team 2002-2003
 *
 * Table of thread labels.
 *
 * ---------------------------------------------------------------------------*/

#include "rts/PosixSource.h"
#include "Rts.h"

#include "ThreadLabels.h"
#include "RtsUtils.h"
#include "Hash.h"
#include "Trace.h"

#include <stdlib.h>
#include <string.h>

#if defined(THREADED_RTS)
static Mutex threadLabels_mutex;
#endif /* THREADED_RTS */

static HashTable * threadLabels = NULL;

void
initThreadLabelTable(void)
{
#if defined(THREADED_RTS)
  initMutex(&threadLabels_mutex);
#endif /* THREADED_RTS */

  if (threadLabels == NULL) {
    threadLabels = allocHashTable();
  }
}

void
freeThreadLabelTable(void)
{
    ACQUIRE_LOCK(&threadLabels_mutex);

    if (threadLabels != NULL) {
        freeHashTable(threadLabels, stgFree);
        threadLabels = NULL;
    }

    RELEASE_LOCK(&threadLabels_mutex);
}

static void
updateThreadLabel(StgThreadID key, void *data)
{
  removeThreadLabel(key);

  ACQUIRE_LOCK(&threadLabels_mutex);

  insertHashTable(threadLabels,key,data);

  RELEASE_LOCK(&threadLabels_mutex);
}

void *
lookupThreadLabel(StgThreadID key)
{
  void * result;
  ACQUIRE_LOCK(&threadLabels_mutex);

  result = lookupHashTable(threadLabels,key);

  RELEASE_LOCK(&threadLabels_mutex);

  return result;
}

void
removeThreadLabel(StgThreadID key)
{
  ACQUIRE_LOCK(&threadLabels_mutex);

  void * old = NULL;
  if ((old = lookupHashTable(threadLabels,key))) {
    removeHashTable(threadLabels,key,old);
    stgFree(old);
  }

  RELEASE_LOCK(&threadLabels_mutex);
}

void
labelThread(Capability *cap   STG_UNUSED,
            StgTSO     *tso   STG_UNUSED,
            char       *label STG_UNUSED)
{
  int len;
  void *buf;

  /* Caveat: Once set, you can only set the thread name to "" */
  len = strlen(label)+1;
  buf = stgMallocBytes(len * sizeof(char), "ThreadLabels.c:labelThread()");
  strncpy(buf,label,len);

  /* Update will free the old memory for us */
  updateThreadLabel(tso->id,buf);

  traceThreadLabel(cap, tso, label);
}