xref: /plan9/sys/src/libthread/id.c (revision f9e1cf08d3be51592e03e639fc848a68dc31a55e)
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; 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 *fmt, ...)
59 {
60 	int fd;
61 	char buf[128];
62 	va_list arg;
63 	Proc *p;
64 	Thread *t;
65 
66 	p = _threadgetproc();
67 	t = p->thread;
68 	if (t->cmdname)
69 		free(t->cmdname);
70 	va_start(arg, fmt);
71 	t->cmdname = vsmprint(fmt, arg);
72 	va_end(arg);
73 	if(t->cmdname && p->nthreads == 1){
74 		snprint(buf, sizeof buf, "#p/%d/args", getpid());
75 		if((fd = open(buf, OWRITE)) >= 0){
76 			write(fd, t->cmdname, strlen(t->cmdname)+1);
77 			close(fd);
78 		}
79 	}
80 }
81 
82 char*
83 threadgetname(void)
84 {
85 	return _threadgetproc()->thread->cmdname;
86 }
87 
88 void**
89 threaddata(void)
90 {
91 	return &_threadgetproc()->thread->udata[0];
92 }
93 
94 void**
95 procdata(void)
96 {
97 	return &_threadgetproc()->udata;
98 }
99 
100 static Lock privlock;
101 static int privmask = 1;
102 
103 int
104 tprivalloc(void)
105 {
106 	int i;
107 
108 	lock(&privlock);
109 	for(i=0; i<NPRIV; i++)
110 		if(!(privmask&(1<<i))){
111 			privmask |= 1<<i;
112 			unlock(&privlock);
113 			return i;
114 		}
115 	unlock(&privlock);
116 	return -1;
117 }
118 
119 void
120 tprivfree(int i)
121 {
122 	if(i < 0 || i >= NPRIV)
123 		abort();
124 	lock(&privlock);
125 	privmask &= ~(1<<i);
126 }
127 
128 void**
129 tprivaddr(int i)
130 {
131 	return &_threadgetproc()->thread->udata[i];
132 }
133