33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
|
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
|
-
+
-
+
-
+
-
+
-
-
+
-
-
+
-
-
+
-
-
+
-
+
-
+
-
-
+
-
+
-
+
-
+
-
-
+
-
+
-
+
|
functionWrapper(struct thread_context *context)
{
context->function(context->object);
free(context);
}
bool
int
of_thread_attr_init(of_thread_attr_t *attr)
{
attr->priority = 0;
attr->stackSize = 0;
return true;
return 0;
}
bool
int
of_thread_new(of_thread_t *thread, const char *name, void (*function)(id),
id object, const of_thread_attr_t *attr)
{
DWORD priority = THREAD_PRIORITY_NORMAL;
struct thread_context *context;
DWORD threadID;
if (attr != NULL && attr->priority != 0) {
if (attr->priority < -1 || attr->priority > 1) {
if (attr->priority < -1 || attr->priority > 1)
errno = EINVAL;
return false;
return EINVAL;
}
if (attr->priority < 0)
priority = THREAD_PRIORITY_LOWEST +
(1.0 + attr->priority) *
(THREAD_PRIORITY_NORMAL - THREAD_PRIORITY_LOWEST);
else
priority = THREAD_PRIORITY_NORMAL +
attr->priority *
(THREAD_PRIORITY_HIGHEST - THREAD_PRIORITY_NORMAL);
}
if ((context = malloc(sizeof(*context))) == NULL) {
if ((context = malloc(sizeof(*context))) == NULL)
errno = ENOMEM;
return false;
return ENOMEM;
}
context->function = function;
context->object = object;
*thread = CreateThread(NULL, (attr != NULL ? attr->stackSize : 0),
(LPTHREAD_START_ROUTINE)functionWrapper, context, 0, &threadID);
if (thread == NULL) {
int errNo;
int error;
switch (GetLastError()) {
case ERROR_NOT_ENOUGH_MEMORY:
errNo = ENOMEM;
error = ENOMEM;
break;
case ERROR_ACCESS_DENIED:
errNo = EACCES;
error = EACCES;
break;
default:
OF_ENSURE(0);
}
free(context);
errno = errNo;
return false;
return error;
}
if (attr != NULL && attr->priority != 0)
OF_ENSURE(!SetThreadPriority(*thread, priority));
return true;
return 0;
}
bool
int
of_thread_join(of_thread_t thread)
{
switch (WaitForSingleObject(thread, INFINITE)) {
case WAIT_OBJECT_0:
CloseHandle(thread);
return true;
return 0;
case WAIT_FAILED:
switch (GetLastError()) {
case ERROR_INVALID_HANDLE:
errno = EINVAL;
return false;
return EINVAL;
default:
OF_ENSURE(0);
}
default:
OF_ENSURE(0);
}
}
bool
int
of_thread_detach(of_thread_t thread)
{
CloseHandle(thread);
return true;
return 0;
}
void
of_thread_set_name(const char *name)
{
}
|