xref: /plan9-contrib/sys/src/libthread/id.c (revision a6a9e07217f318acf170f99684a55fba5200524f)
1 #include <u.h>
2 #include <libc.h>
3 #include <thread.h>
4 #include "threadimpl.h"
5 
6 int
7 threadid(void)
8 {
9 	return _threadgetproc()->thread->id;
10 }
11 
12 int
13 threadpid(int id)
14 {
15 	int pid;
16 	Proc *p;
17 	Thread *t;
18 
19 	if (id < 0)
20 		return -1;
21 	if (id == 0)
22 		return _threadgetproc()->pid;
23 	lock(&_threadpq.lock);
24 	for (p = _threadpq.head; p->next; p = p->next){
25 		lock(&p->lock);
26 		for (t = p->threads.head; t; t = t->nextt)
27 			if (t->id == id){
28 				pid = p->pid;
29 				unlock(&p->lock);
30 				unlock(&_threadpq.lock);
31 				return pid;
32 			}
33 		unlock(&p->lock);
34 	}
35 	unlock(&_threadpq.lock);
36 	return -1;
37 }
38 
39 int
40 threadsetgrp(int ng)
41 {
42 	int og;
43 	Thread *t;
44 
45 	t = _threadgetproc()->thread;
46 	og = t->grp;
47 	t->grp = ng;
48 	return og;
49 }
50 
51 int
52 threadgetgrp(void)
53 {
54 	return _threadgetproc()->thread->grp;
55 }
56 
57 void
58 threadsetname(char *name)
59 {
60 	int fd, n;
61 	char buf[128], *s;
62 	Proc *p;
63 	Thread *t;
64 
65 	p = _threadgetproc();
66 	t = p->thread;
67 	if (t->cmdname)
68 		free(t->cmdname);
69 	t->cmdname = strdup(name);
70 	if(p->nthreads == 1){
71 		snprint(buf, sizeof buf, "#p/%d/args", getpid());
72 		if((fd = open(buf, OWRITE)) >= 0){
73 			snprint(buf, sizeof buf, "%s [%s]", argv0, name);
74 			n = strlen(buf)+1;
75 			s = strchr(buf, ' ');
76 			if(s)
77 				*s = '\0';
78 			write(fd, buf, n);
79 			close(fd);
80 		}
81 	}
82 }
83 
84 char*
85 threadgetname(void)
86 {
87 	return _threadgetproc()->thread->cmdname;
88 }
89 
90 void**
91 threaddata(void)
92 {
93 	return &_threadgetproc()->thread->udata[0];
94 }
95 
96 void**
97 procdata(void)
98 {
99 	return &_threadgetproc()->udata;
100 }
101 
102 static Lock privlock;
103 static int privmask = 1;
104 
105 int
106 tprivalloc(void)
107 {
108 	int i;
109 
110 	lock(&privlock);
111 	for(i=0; i<NPRIV; i++)
112 		if(!(privmask&(1<<i))){
113 			privmask |= 1<<i;
114 			unlock(&privlock);
115 			return i;
116 		}
117 	unlock(&privlock);
118 	return -1;
119 }
120 
121 void
122 tprivfree(int i)
123 {
124 	if(i < 0 || i >= NPRIV)
125 		abort();
126 	lock(&privlock);
127 	privmask &= ~(1<<i);
128 }
129 
130 void**
131 tprivaddr(int i)
132 {
133 	return &_threadgetproc()->thread->udata[i];
134 }
135