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