summaryrefslogtreecommitdiff
path: root/rts/ThreadLabels.c
blob: 7a06580efcb7105a69a5de08e27c1926f3733089 (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
109
110
111
112
/* -----------------------------------------------------------------------------
 * ThreadLabels.c
 *
 * (c) The GHC Team 2002-2003
 *
 * Table of thread labels.
 *
 * ---------------------------------------------------------------------------*/

#include "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(DEBUG)

#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(StgWord key, void *data)
{
  removeThreadLabel(key);

  ACQUIRE_LOCK(&threadLabels_mutex);

  insertHashTable(threadLabels,key,data);

  RELEASE_LOCK(&threadLabels_mutex);
}

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

  result = lookupHashTable(threadLabels,key);

  RELEASE_LOCK(&threadLabels_mutex);

  return result;
}

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

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

  RELEASE_LOCK(&threadLabels_mutex);
}

#endif /* DEBUG */

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

  /* Caveat: Once set, you can only set the thread name to "" */
  len = strlen(label)+1;
  buf = stgMallocBytes(len * sizeof(char), "Schedule.c:labelThread()");
  strncpy(buf,label,len);
  /* Update will free the old memory for us */
  updateThreadLabel(tso->id,buf);
#endif
  traceThreadLabel(cap, tso, label);
}