xref: /plan9/sys/src/libthread/id.c (revision 6ca6a3e703ee2ec4aed99c2177f71d7f127da6d9)
1 #include <u.h>
2 #include <libc.h>
3 #include <thread.h>
4 #include "threadimpl.h"
5 #include <tos.h>
6 
7 int
threadid(void)8 threadid(void)
9 {
10 	return _threadgetproc()->thread->id;
11 }
12 
13 int
threadpid(int id)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
threadsetgrp(int ng)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
threadgetgrp(void)53 threadgetgrp(void)
54 {
55 	return _threadgetproc()->thread->grp;
56 }
57 
58 void
threadsetname(char * fmt,...)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*
threadgetname(void)84 threadgetname(void)
85 {
86 	Proc *p;
87 
88 	if((p = _threadgetproc()) && p->thread)
89 		return p->thread->cmdname;
90 	return nil;
91 }
92 
93 void**
threaddata(void)94 threaddata(void)
95 {
96 	return &_threadgetproc()->thread->udata[0];
97 }
98 
99 void**
_workerdata(void)100 _workerdata(void)
101 {
102 	return &_threadgetproc()->wdata;
103 }
104 
105 void**
procdata(void)106 procdata(void)
107 {
108 	return &_threadgetproc()->udata;
109 }
110 
111 static Lock privlock;
112 static int privmask = 1;
113 
114 int
tprivalloc(void)115 tprivalloc(void)
116 {
117 	int i;
118 
119 	lock(&privlock);
120 	for(i=0; i<NPRIV; i++)
121 		if(!(privmask&(1<<i))){
122 			privmask |= 1<<i;
123 			unlock(&privlock);
124 			return i;
125 		}
126 	unlock(&privlock);
127 	return -1;
128 }
129 
130 void
tprivfree(int i)131 tprivfree(int i)
132 {
133 	if(i < 0 || i >= NPRIV)
134 		abort();
135 	lock(&privlock);
136 	privmask &= ~(1<<i);
137 }
138 
139 void**
tprivaddr(int i)140 tprivaddr(int i)
141 {
142 	return &_threadgetproc()->thread->udata[i];
143 }
144