xref: /plan9/sys/src/libthread/id.c (revision ff8c3af2f44d95267f67219afa20ba82ff6cf7e4)
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 			n = strlen(name)+1;
74 			write(fd, name, n);
75 			close(fd);
76 		}
77 	}
78 }
79 
80 char*
81 threadgetname(void)
82 {
83 	return _threadgetproc()->thread->cmdname;
84 }
85 
86 void**
87 threaddata(void)
88 {
89 	return &_threadgetproc()->thread->udata[0];
90 }
91 
92 void**
93 procdata(void)
94 {
95 	return &_threadgetproc()->udata;
96 }
97 
98 static Lock privlock;
99 static int privmask = 1;
100 
101 int
102 tprivalloc(void)
103 {
104 	int i;
105 
106 	lock(&privlock);
107 	for(i=0; i<NPRIV; i++)
108 		if(!(privmask&(1<<i))){
109 			privmask |= 1<<i;
110 			unlock(&privlock);
111 			return i;
112 		}
113 	unlock(&privlock);
114 	return -1;
115 }
116 
117 void
118 tprivfree(int i)
119 {
120 	if(i < 0 || i >= NPRIV)
121 		abort();
122 	lock(&privlock);
123 	privmask &= ~(1<<i);
124 }
125 
126 void**
127 tprivaddr(int i)
128 {
129 	return &_threadgetproc()->thread->udata[i];
130 }
131