├── .gitignore
├── LICENSE
├── README.md
├── _config.yml
├── doc
├── logo-mthread.png
└── logo.png
├── many-one
├── Makefile
├── README.md
├── data
│ ├── 1.txt
│ ├── 2.txt
│ └── 3.txt
├── docs
│ ├── doxy-config
│ ├── logo.png
│ └── many-to-one.png
├── include
│ ├── interrupt.h
│ ├── mangle.h
│ ├── mthread.h
│ ├── queue.h
│ ├── stack.h
│ ├── types.h
│ └── utils.h
├── run_tests.sh
├── src
│ ├── attr.c
│ ├── interrupt.c
│ ├── mthread.c
│ ├── queue.c
│ ├── spin_lock.c
│ ├── stack.c
│ └── utils.c
├── test
│ ├── detach_state_test.c
│ ├── matrix_test.c
│ ├── robust_test.c
│ └── spin_test.c
└── valgrind.sh
└── one-one
├── Makefile
├── README.md
├── docs
├── doxy-config
├── logo.png
└── one-to-one.png
├── include
├── mthread.h
├── queue.h
├── stack.h
├── types.h
└── utils.h
├── run_tests.sh
├── src
├── attr.c
├── cond.c
├── mthread.c
├── mutex.c
├── queue.c
├── sem.c
├── spin_lock.c
├── stack.c
└── utils.c
├── test
├── condvar_test.c
├── mutex_test.c
├── performance_test.c
├── philosophers.c
├── robust_test.c
├── semaphore_test.c
└── spin_test.c
└── valgrind.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore local resources
2 | Resources/
3 | many-one/bin/
4 | many-one/obj/*.o
5 | one-one/bin/
6 | one-one/obj/*.o
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | [](https://github.com/mayank-02/multithreading-library)
6 | 
7 | [](https://opensource.org/licenses/GPL-3.0)
8 |
9 | A lightweight C library based on one-one and many-one model for threading.
10 |
11 | ## Contents
12 |
13 | + [Building](#building)
14 | + [Using mthread in your project](#using-mthread-in-your-project)
15 | + [Usage and examples](#usage-and-examples)
16 | + [API documentation](#api-documentation)
17 | + [Running tests](#running-tests)
18 | + [Time and space complexity](#time-and-space-complexity)
19 | + [Development and contributing](#development-and-contributing)
20 | + [Acknowledgements](#acknowledgements)
21 |
22 | ## Building
23 |
24 | mthread uses make to build libraries (static and shared) and binaries (for tests).
25 | Execute following commands to build mthread using make:
26 |
27 | ``` bash
28 | make
29 | ```
30 |
31 | This will create binaries in `bin/` directory and libraries (static and shared) in the current directory.
32 |
33 | Optionally, you can run `sudo make install` to install mthread library on your machine (on Linux, this will usually install it to `usr/local/lib` and `usr/local/include`).
34 |
35 | ## Using mthread in your project
36 |
37 | You can use mthread in you project by either directly copying header and source files from [one-one/](one-one/), or by linking mthread library (see [Building](#building) for instructions how to build mthread libraries).
38 | In any case, only thing that you have to do in your source files is to include `mthread.h`.
39 |
40 | To get you started quickly, let's take a look at a few ways to get a simple Hello World project working.
41 |
42 | Our Hello World project has just one source file, `example.c` file, and it looks like this:
43 |
44 | ```c
45 | #include
46 | #include "mthread.h"
47 |
48 | void worker(void) {
49 | printf("Hello World!\n");
50 | mthread_exit(NULL);
51 | }
52 |
53 | int main() {
54 | mthread_t tid;
55 | mthread_init();
56 | mthread_create(&tid, NULL, worker, NULL);
57 | mthread_join(tid, NULL);
58 | return 0;
59 | }
60 | ```
61 |
62 | ### Approach #1: Copying mthread header file and static library
63 |
64 | Instead of copying mthread source files, you could copy the static library or a shared object (check [Building](#building) on how to create static library / shared object). We also need to copy mthread header files. We get following project structure:
65 | In case of a static library:
66 |
67 | ```
68 | example.c -> your program
69 | mthread.h -> copied from mthread
70 | libmthread.a -> copied from mthread
71 | ```
72 |
73 | In case of shared object:
74 |
75 | ```
76 | example.c -> your program
77 | mthread.h -> copied from mthread
78 | libmthread.so -> copied from mthread
79 | ```
80 |
81 | Now you can compile it with
82 |
83 | ```bash
84 | gcc example.c -o example -L. -llibmthread.
85 | ```
86 |
87 | ### Approach #2: Install mthread library on machine (TODO)
88 |
89 | Alternatively, you could avoid copying any mthread files and instead install libraries by running `sudo make install` (check [Building](#building)). Now, all you have to do to compile your project is `gcc example.c -o example -llibmthread`.
90 | If you get error message like `cannot open shared object file: No such file or directory`, make sure that your linker includes path where mthread was installed.
91 |
92 | ## Usage and examples
93 |
94 | To know more about how to use mthread library, check out the various tests written in the `test` directory of each model.
95 |
96 | ## API documentation
97 |
98 | + Types are named **mthread\_[type]\_t** (examples: mthread_t, mthread_cond_t, etc.)
99 |
100 | + Functions are called **mthread\_[type]\_[action]** with a few exceptions that are mthread_[action] and pertain to the API in whole and not a specific type.
101 | + Constants are named **MTHREAD\_[NAME]**
102 |
103 | The mthreads API is inherently simple. Not in the sense that it makes multi-threaded (MT) programming a breeze (I doubt this is possible), but in the sense that it provides everything that's needed to write MT programs, and only that.
104 |
105 | To generate the latest API documentation yourself from the source, you need to have [doxygen](www.doxygen.org) installed.
106 | Position yourself in the root directory of the model you are interested in.
107 | Then run `make docs`. This will output a `/docs/html` and `/docs/latex` folder.
108 | Then open `docs/html/index.html` file with your favorite browser.
109 |
110 | Alternatively, you can directly check [mthread.h](one-one/include/mthread.h) for one-one and [mthread.h](many-one/include/mthread.h) for many-one
111 |
112 | ## Running tests
113 |
114 | Check [Building](#building) to see how to build binaries.
115 | To run each test, just run `./run_tests` from the root directory of both models.
116 | Default values are used for tests requiring command line arguments.
117 |
118 | ## Time and space complexity
119 |
120 | The library maintains a queue for internal book keeping. Thus, the functions have different time complexities. They have a best case time complexity of `O(1)` and worst case time complexity of `O(N)`, N being the number of threads spawned. Space complexity is `O(N)`.
121 |
122 | ## Implementation Details
123 |
124 | + To know the implementation details of one-one threading model, please check out it's [README](one-one/README.md)
125 |
126 | + To know the implementation details of many-one threading model, please check out it's [README](many-one/README.md)
127 |
128 | ## Development and contributing
129 |
130 | Feel free to send pull requests and raise issues.
131 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
--------------------------------------------------------------------------------
/doc/logo-mthread.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayank-02/multithreading-library/3df2df3068c80851103e1d910e0d21b5ac8918ff/doc/logo-mthread.png
--------------------------------------------------------------------------------
/doc/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayank-02/multithreading-library/3df2df3068c80851103e1d910e0d21b5ac8918ff/doc/logo.png
--------------------------------------------------------------------------------
/many-one/Makefile:
--------------------------------------------------------------------------------
1 | SRC_DIR := src
2 | OBJ_DIR := obj
3 | TEST_DIR := test
4 | BIN_DIR := bin
5 | DOC_DIR := docs
6 |
7 | SRC := $(wildcard $(SRC_DIR)/*.c)
8 | # $(info SRC is $(SRC))
9 |
10 | OBJ := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)
11 | # $(info OBJ is $(OBJ))
12 |
13 | TEST_SRC := $(wildcard $(TEST_DIR)/*.c)
14 | # $(info TEST_SRC is $(TEST_SRC))
15 |
16 | TEST_OBJ := $(TEST_SRC:$(TEST_DIR)/%.c=$(TEST_DIR)/%.o)
17 | # $(info TEST_OBJ is $(TEST_OBJ))
18 |
19 | EXE := $(addprefix $(BIN_DIR)/, $(notdir $(basename $(TEST_SRC))))
20 | # $(info EXE is $(EXE))
21 |
22 | CPPFLAGS := -I include
23 | CFLAGS := -g -Wall -fpic
24 | # -g : For debugging purposes
25 | # -Wall : Print all warnings
26 | # -fpic : Use Position Independent Code. It means that the generated machine code is not dependent on being located at a specific address in order to work Ex. Jumps would be generated as relative rather than absolute
27 | TESTCFLAGS := -Wno-int-to-pointer-cast -Wno-pointer-to-int-cast -Wno-return-type
28 | LIB := libmthread.a
29 | LIBSO := libmthread.so
30 | LDFLAGS := -L.
31 | LDLIBS := -lm
32 |
33 | CC := gcc
34 | AR := /usr/bin/ar
35 | RANLIB := /usr/bin/ranlib
36 | .PHONY: all clean lib exe docs
37 |
38 | DEBUG := 0
39 | ifeq ($(DEBUG),1)
40 | CFLAGS += -DDEBUG
41 | endif
42 |
43 | all: $(LIB) $(EXE) $(LIBSO)
44 |
45 | $(LIBSO) : $(OBJ)
46 | $(CC) -shared $(OBJ) -o $@
47 |
48 | $(LIB) : $(OBJ)
49 | $(AR) rcs $(LIB) $(OBJ)
50 | $(RANLIB) $(LIB)
51 |
52 | $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c | $(OBJ_DIR)
53 | $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
54 |
55 | $(BIN_DIR)/%: $(TEST_DIR)/%.o $(LIB)
56 | $(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@
57 |
58 | $(TEST_DIR)/%.o: $(TEST_DIR)/%.c | $(OBJ_DIR)
59 | $(CC) $(CPPFLAGS) $(CFLAGS) $(TESTCFLAGS) -c $< -o $@
60 |
61 | $(OBJ_DIR):
62 | mkdir $@
63 |
64 | docs:
65 | doxygen $(DOC_DIR)/doxy-config
66 |
67 | clean:
68 | $(RM) -rf $(OBJ) $(TEST_OBJ) $(LIB) $(LIBSO) $(EXE) $(DOC_DIR)/html $(DOC_DIR)/latex
--------------------------------------------------------------------------------
/many-one/README.md:
--------------------------------------------------------------------------------
1 | # Many-One Threading Model
2 |
3 | 
4 |
5 | ## Thread Library Initialisation
6 |
7 | + `mthread_init()` initializes the mthread library. It has to be the first mthread API function call in an application, and is mandatory. It's usually done at the begin of the `main()` function of the application. This implicitly initialises the data structures and transforms the single execution unit of the current process into a thread (the 'main' thread). It returns 0 on success.
8 |
9 | ## Thread Creation
10 |
11 | + In the many-to-one model all user level threads execute on the same kernel thread. The process can only run one user-level thread at a time because there is only one kernel-level thread associated with the process. The kernel has no knowledge of user-level threads.
12 |
13 | + To store information about a single thread, a thread control block (TCB) holding information about the state of the thread (its set of registers), information about its stack (a pointer to the thread's stack area and size), and the status of the thread (whether it is running, ready to run, or has exited) is used. Since there will be multiple threads active at the same time, the thread control blocks are stored in a FIFO queue. On creation of the every thread using `mthread_create()`, a TCB is allocated and initialized accordingly.
14 |
15 | + The new user level thread terminates in one of the following ways:
16 | + It calls `mthread_exit()`, specifying an exit status value that is available to another thread in the same process that calls `mthread_join()`.
17 | + It returns from `start_routine()`. This is equivalent to calling `mthread_exit()` with the value supplied in the return statement.
18 | + Any of the threads in the process calls `exit(3)`, or the main thread performs a return from `main()`. This causes the termination of all threads in the process.
19 |
20 | + Therefore, we write a wrapper function - `mthread_start()` which grabs the argument from the TCB and then invoke the actual start function, passing it the required argument. In addition, we simply invoke `mthread_exit()` after the thread returns from the previous call to the start function with the result. For this indirection, we need to make the program counter (EIP) point to this function instead of the actual start function. For this, we manually change the **JB_PC** of the `jmpbuf` array.
21 |
22 | + We allocate the memory that is to be used for the thread's stack using `mmap(2)` rather than `malloc(3)` because `mmap(2)` allocates a block of memory that starts on a page boundary and is a multiple of the page size. This is useful sicne we want to establish a guard page (a page with protection PROT_NONE) at the end of the stack using `mprotect(2)`.
23 |
24 | + The stack pointer passed to the stack pointer of the `jmpbuf` structure must reference the top of the stack, since on most processors the stack grows down. This is done by adding the size of the region to the base of the mmap'ed region. To avoid a memory leak, the stack must be freed once the thread has exited.
25 |
26 | + Linux systems are usually equipped with a libc that includes a security feature to protect the addresses stored in jump buffers. This security feature "mangles" (i.e. encrypts) a pointer before saving it in a `jmp_buf`. Thus, we also have to mangle our new stack pointer and program counter before we can write it into a jump buffer, otherwise decryption (and subsequent uses) will fail. To mangle a pointer before writing it into the jump buffer, we make use of the `mangle` function.
27 |
28 | + To change attributes of a thread like the stack size, stack base, name for user level debugging and it's detach state, an attribute object of threads passed as the second argument to `mthread_create()`. The user allocates it, and then calls `mthread_attr_init` to intialize it and `mthread_attr_destroy` to clean it up. For more info, refer thread attribute handling.
29 |
30 | + On succesful thread creation, the thread library provides a **thread handle** as a return value which can be further used in different thread control functions.
31 |
32 | ## Scheduling
33 |
34 | + A hybrid model between cooperative and preemptive scheduling is implemented where a running thread may `mthread_yield()` or be preempted by a timer.
35 |
36 | + Once multiple threads are running, to switch between different threads we use the library functions `sigsetjmp(3)` and `siglongjmp(3)`. In a nutshell, `sigsetjmp` saves the current state of a thread into a `jmp_buf` structure. `siglongjmp` uses this structure to restore (jump back) to a previously saved state. More precisely, we have the currently executing thread call `sigsetjmp(3)` and save the result in the thread's TCB. Then, our scheduler can pick another thread, and use the saved `jmp_buf` of that thread together with `siglongjmp(3)` to resume the execution of the new thread.
37 |
38 | + The process of picking another thread is called scheduling. In our system, we have a very simply scheduler. Just cycle through the available threads in a round robin fashion, giving an equal, fair share to each thread.
39 |
40 | + To periodically switch to the next user level thread, we make use of signals. More precisely, we use the `setitimer` function to set up a periodic timer that sends a `SIGVTALRM` signal every X milliseconds (here, X is 10ms). When the timer expires the kernel will send a signal to the process. The scheduler is registered as a signal handler for the timer signal.
41 |
42 | ## Thread Attribute Handling
43 |
44 | Attribute objects are used in mthread to store attributes for to be spawned threads. They are stand-alone/unbound attribute objects i.e. they cannot modify attributes of existing threads. The following attribute fields exists in attribute objects:
45 |
46 | + MTHREAD_ATTR_NAME (read-write) [char *]
47 | Name of thread (up to 64 characters are stored only), mainly for debugging purposes.
48 |
49 | + MTHREAD_ATTR_JOINABLE (read-write) \[int\]
50 | The thread detachment type, JOINABLE indicates a joinable thread, DETACHED indicates a detached thread.
51 |
52 | + MTHREAD_ATTR_STACK_SIZE (read-write) \[unsigned int\]
53 | The thread stack size in bytes. Use lower values with great care!
54 |
55 | + MTHREAD_ATTR_STACK_ADDR (read-write) \[char *\]
56 | A pointer to the lower address of a chunk of malloc(3)'ed memory for the stack.
57 |
58 | `mthread_attr_t mthread_attr_new(void);`
59 | This returns a new unbound attribute object. An implicit mthread_attr_init() is done on it. Any queries on this object just fetch stored attributes from it. And attribute modifications just change the stored attributes. Use such attribute objects to pre-configure attributes for to be spawned threads.
60 |
61 | `int mthread_attr_init(mthread_attr_t attr);`
62 | This initializes an attribute object attr to the default values:
63 | MTHREAD_ATTR_NAME := 'Unknown', MTHREAD_ATTR_JOINABLE := JOINABLE, MTHREAD_ATTR_STACK_SIZE := DEFAULT and MTHREAD_ATTR_STACK_ADDR := NULL.
64 |
65 | `int mthread_attr_set(mthread_attr_t attr, int field, ...);`
66 | This sets the attribute field in attr to a value specified as an additional argument on the variable argument list. The following attribute fields and argument pairs can be used:
67 |
68 | | Attribute | Type |
69 | |---------------------------|--------------|
70 | | MTHREAD_ATTR_NAME | char * |
71 | | MTHREAD_ATTR_JOINABLE | int |
72 | | MTHREAD_ATTR_STACK_SIZE | unsigned int |
73 | | MTHREAD_ATTR_STACK_ADDR | void * |
74 |
75 | `int mthread_attr_get(mthread_attr_t attr, int field, ...);`
76 | This retrieves the attribute field in attr and stores its value in the variable specified through a pointer in an additional argument on the variable argument list. The following fields and argument pairs can be used:
77 |
78 | | Attribute | Type |
79 | |---------------------------|---------------|
80 | | MTHREAD_ATTR_NAME | char ** |
81 | | MTHREAD_ATTR_JOINABLE | int * |
82 | | MTHREAD_ATTR_STACK_SIZE | unsigned int *|
83 | | MTHREAD_ATTR_STACK_ADDR | void ** |
84 |
85 | `int mthread_attr_destroy(mthread_attr_t attr);`
86 | This destroys a attribute object attr. After this attr is no longer a valid attribute object.
87 |
88 | ## Thread Joining
89 |
90 | + The `mthread_join()` function waits for the thread specified by thread to terminate. If that thread has already terminated, then `mthread_join()` returns immediately. The thread specified by thread must be joinable.
91 |
92 | + A thread may have to wait for the completion of another thread. If the caller thread waits for an incomplete target thread to join, then it will halt till the target thread exits. This is done by changing the state of the thread to WAITING. Once the target thread has finished, the current thread will be signaled and it's state will be changed to READY again.
93 |
94 | + Even if a thread has finished execution, none of its allocated resources are freed. The resources of the thread are released only after the program exits to improve time complexity.
95 |
96 | + A thread must be joined on only once. Any further joins on an already joined thread will return errors.
97 |
98 | + All of the threads in a process are peers: any thread can join with any other thread in the process.
99 |
100 | ## Thread Signals
101 |
102 | + Signals may be sent to a specific thread using `mthread_kill()`.
103 |
104 | + All signals which aren't meant for the current thread are made pending for that thread. They are raised when the thread is scheduled.
105 |
106 | + Note : Signal dispositions and actions are process-wide: if an unhandled signal is delivered to a thread, then it will affect (terminate, stop, continue, be ignored in) all members of the thread group.
107 |
108 | ## Thread Exiting
109 |
110 | + As mentioned previously, a thread can exit using the `mthread_exit()` function. The thread can also return a value while it is exiting, to be returned to the thread joining on it. This is done by storing it's result in the TCB and marking the state of the thread as FINISHED.
111 |
112 | + Any threads joined on the thread exiting are signaled the about the completion of this thread.
113 |
114 | ## Thread Yielding
115 |
116 | + Yield execution control to next thread by simply calling `mthread_yield()`. It is simply a wrapper for a `raise(SIGVTALRM)`
117 |
118 | ## Thread Detachment
119 |
120 | + The `mthread_detach()` function marks the thread passed as argument as detached. Any other thread trying to join on a detached thread will result in an error.
121 |
122 | ## Thread Equality
123 |
124 | + The `mthread_equal()` function checks whether the threads identified by their thread handles are the same or not. Returns 0 if equal and non-zero if not.
125 |
126 | ## Synchronisation Primitives
127 |
128 | ## Spinlocks
129 |
130 | A spinlock is a lock which causes a thread trying to acquire it to simply wait in a loop ("spin") while repeatedly checking if the lock is available. The advantage of a spinlock is that the thread is kept active and does not enter a sleep-wait for a mutex to become available, thus can perform better in certain cases than typical blocking-sleep-wait style mutexes.
131 |
132 | Functions used in conjunction with the spinlock:
133 |
134 | Creating/Destroying:
135 | `mthread_spinlock_init()`
136 | `mthread_spinlock_destroy()`
137 |
138 | Attempt to lock the spinlock (returns immediately with EBUSY if locked):
139 | `mthread_spinlock_trylock()`
140 |
141 | Lock the spinlock (blocks until spinlock is unlocked):
142 | `mthread_spinlock_lock()`
143 |
144 | Unlock the spinlock:
145 | `mthread_spinlock_unlock()`
146 |
--------------------------------------------------------------------------------
/many-one/data/1.txt:
--------------------------------------------------------------------------------
1 | 3 3
2 | 1 2 4
3 | 4 2 3
4 | 6 5 8
5 | 3 3
6 | 5 8 4
7 | 4 1 3
8 | 3 2 5
--------------------------------------------------------------------------------
/many-one/data/2.txt:
--------------------------------------------------------------------------------
1 | 11 11
2 | 22 78 95 32 29 85 60 19 92 14 8
3 | 85 38 57 49 89 46 15 56 85 53 33
4 | 36 60 19 27 4 6 57 83 94 79 13
5 | 41 63 43 27 76 14 71 90 22 8 81
6 | 31 10 70 78 25 26 15 30 11 51 43
7 | 30 78 47 88 87 82 35 67 96 28 30
8 | 91 7 58 5 79 49 79 87 30 62 97
9 | 0 40 75 26 55 57 89 6 0 20 37
10 | 0 60 24 82 95 43 78 76 26 69 83
11 | 84 26 62 33 57 2 15 20 51 15 12
12 | 78 93 68 36 83 26 36 55 15 36 67
13 | 11 11
14 | 5 99 43 58 79 0 0 75 46 7 25
15 | 34 36 4 40 36 67 24 66 11 1 37
16 | 51 89 96 76 4 75 14 65 22 71 64
17 | 17 29 95 18 81 22 16 88 99 50 76
18 | 3 43 64 71 67 31 34 21 20 85 10
19 | 16 13 66 44 79 31 66 50 47 84 32
20 | 94 54 13 16 22 54 67 24 30 71 67
21 | 95 94 87 78 28 60 50 13 22 66 78
22 | 88 10 57 71 29 59 70 65 91 64 19
23 | 57 32 93 63 99 17 45 70 37 92 16
24 | 76 22 44 36 72 9 58 91 87 98 1
25 |
--------------------------------------------------------------------------------
/many-one/docs/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayank-02/multithreading-library/3df2df3068c80851103e1d910e0d21b5ac8918ff/many-one/docs/logo.png
--------------------------------------------------------------------------------
/many-one/docs/many-to-one.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayank-02/multithreading-library/3df2df3068c80851103e1d910e0d21b5ac8918ff/many-one/docs/many-to-one.png
--------------------------------------------------------------------------------
/many-one/include/interrupt.h:
--------------------------------------------------------------------------------
1 | #ifndef _INTERRUPT_H_
2 | #define _INTERRUPT_H_
3 |
4 | #include
5 |
6 | /// Timer interval
7 | #define TIMER (suseconds_t) 10000
8 |
9 | typedef struct itimerval mthread_timer_t;
10 |
11 | void interrupt_enable(mthread_timer_t *timer);
12 |
13 | void interrupt_disable(mthread_timer_t *timer);
14 |
15 | #endif
--------------------------------------------------------------------------------
/many-one/include/mangle.h:
--------------------------------------------------------------------------------
1 | #ifndef _MANGLE_H_
2 | #define _MANGLE_H_
3 |
4 | #ifdef __x86_64__
5 | /* Pointer mangling for 64 bit Intel architecture */
6 | #define JB_SP 6
7 | #define JB_PC 7
8 | static long int mangle(long int p) {
9 | long int ret;
10 | asm(" mov %1, %%rax;\n"
11 | " xor %%fs:0x30, %%rax;"
12 | " rol $0x11, %%rax;"
13 | " mov %%rax, %0;"
14 | : "=r"(ret)
15 | : "r"(p)
16 | : "%rax"
17 | );
18 | return ret;
19 | }
20 | #else
21 | /* Pointer mangling for 32 bit Intel architecture */
22 | #define JB_SP 4
23 | #define JB_PC 5
24 | static unsigned int mangle(unsigned int addr) {
25 | unsigned int ret ;
26 | asm volatile("xor %%gs:0x18,%0\n"
27 | "rol $0x9,%0\n"
28 | : "=g" (ret)
29 | : "0" (addr));
30 | return ret;
31 | }
32 | #endif
33 |
34 | #endif
--------------------------------------------------------------------------------
/many-one/include/mthread.h:
--------------------------------------------------------------------------------
1 | #ifndef _MTHREAD_H_
2 | #define _MTHREAD_H_
3 |
4 | #include "types.h"
5 |
6 | enum {
7 | DETACHED,
8 | JOINABLE,
9 | };
10 |
11 | /// Operation to perform on thread attribute structure
12 | enum {
13 | MTHREAD_ATTR_GET,
14 | MTHREAD_ATTR_SET
15 | };
16 |
17 | /// Attribute to read/write in thread attribute structure
18 | enum {
19 | MTHREAD_ATTR_NAME, /* RW [char *] name of thread */
20 | MTHREAD_ATTR_JOINABLE, /* RW [int] detachment type */
21 | MTHREAD_ATTR_STACK_SIZE, /* RW [size_t] stack */
22 | MTHREAD_ATTR_STACK_ADDR /* RW [void *] stack lower */
23 | };
24 |
25 | /* Thread attribute functions */
26 | struct mthread_attr;
27 | typedef struct mthread_attr mthread_attr_t;
28 |
29 | mthread_attr_t *mthread_attr_new(void);
30 | int mthread_attr_init(mthread_attr_t *attr);
31 | int mthread_attr_set(mthread_attr_t *attr, int field, ...);
32 | int mthread_attr_get(mthread_attr_t *attr, int field, ...);
33 | int mthread_attr_destroy(mthread_attr_t *attr);
34 |
35 | /**
36 | * Perform any initialization needed. Should be called exactly
37 | * once, before any other mthread functions.
38 | */
39 | int mthread_init(void);
40 |
41 | /**
42 | * Create a new thread starting at the routine given, which will
43 | * be passed arg. The new thread does not execute immediatly.
44 | */
45 | int mthread_create(mthread_t *thread, const mthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
46 |
47 | /**
48 | * Wait until the specified thread has exited.
49 | * Returns the value returned by that thread's
50 | * start function.
51 | */
52 | int mthread_join(mthread_t thread, void **retval);
53 |
54 | /**
55 | * Yield to scheduler
56 | */
57 | void mthread_yield(void);
58 |
59 | /**
60 | * Exit the calling thread with return value retval.
61 | */
62 | void mthread_exit(void *retval);
63 |
64 | /**
65 | * Send signal specified by sig to thread
66 | */
67 | int mthread_kill(mthread_t thread, int sig);
68 |
69 | /**
70 | * Mark the thread as detached
71 | */
72 | int mthread_detach(mthread_t thread);
73 |
74 | /**
75 | * Compare Thread IDs
76 | */
77 | int mthread_equal(mthread_t t1, mthread_t t2);
78 |
79 | /* Synchronisation Primitives */
80 | struct mthread_spinlock;
81 | typedef struct mthread_spinlock mthread_spinlock_t;
82 |
83 | /*
84 | * Initialise the spinlock
85 | */
86 | int mthread_spin_init(mthread_spinlock_t *lock);
87 |
88 | /*
89 | * Lock the spinlock
90 | */
91 | int mthread_spin_lock(mthread_spinlock_t *lock);
92 |
93 | /*
94 | * Try locking the spinlock
95 | */
96 | int mthread_spin_trylock(mthread_spinlock_t *lock);
97 |
98 | /*
99 | * Unlock the spinlock
100 | */
101 | int mthread_spin_unlock(mthread_spinlock_t *lock);
102 |
103 | #endif
--------------------------------------------------------------------------------
/many-one/include/queue.h:
--------------------------------------------------------------------------------
1 | #include "mthread.h"
2 |
3 | /// Node of a queue
4 | typedef struct node {
5 | /// TCB
6 | mthread *thd;
7 | /// Pointer to next node
8 | struct node *next;
9 | } node;
10 |
11 | /// Queue
12 | typedef struct queue {
13 | /// Count of nodes in the queue
14 | int count;
15 | /// Pointer to head node
16 | node *head;
17 | /// Pointer to tail node
18 | node *tail;
19 | } queue;
20 |
21 | void initialize(queue *q);
22 |
23 | int isempty(queue *q);
24 |
25 | void enqueue(queue *q, mthread *thd);
26 |
27 | mthread *dequeue(queue *q);
28 |
29 | int getcount(queue *q);
30 |
31 | void display(queue *q);
32 |
33 | mthread *search_on_tid(queue *q, pid_t tid);
34 |
35 | void destroy(queue *q);
--------------------------------------------------------------------------------
/many-one/include/stack.h:
--------------------------------------------------------------------------------
1 | #ifndef _STACK_H_
2 | #define _STACK_H_
3 |
4 | size_t get_stack_size(void);
5 |
6 | void * allocate_stack(size_t stack_size);
7 |
8 | int deallocate_stack(void *base, size_t stack_size);
9 |
10 | #endif
--------------------------------------------------------------------------------
/many-one/include/types.h:
--------------------------------------------------------------------------------
1 | #ifndef _TYPES_H_
2 | #define _TYPES_H_
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | /// Maximum threads that can be created
9 | #define MTHREAD_MAX_THREADS 128
10 |
11 | /// Minimum stack for each thread
12 | #define MTHREAD_MIN_STACK 64 * 1024
13 |
14 | /// Maximium length of name of thread
15 | #define MTHREAD_TCB_NAMELEN 128
16 |
17 | /// Default attribute of thread
18 | #define MTHREAD_ATTR_DEFAULT (NULL)
19 |
20 | #define FALSE (0)
21 | #define TRUE (!FALSE)
22 |
23 | /// States of a thread
24 | typedef enum mthread_state {
25 | RUNNING = 0,
26 | READY,
27 | FINISHED,
28 | WAITING
29 | } mthread_state_t;
30 |
31 | /// Thread Handle
32 | typedef pid_t mthread_t;
33 |
34 | /// Thread Control Block
35 | typedef struct mthread {
36 | /// Thread ID
37 | mthread_t tid;
38 |
39 | /// Thread State
40 | mthread_state_t state;
41 |
42 | /// Start position of the code to be executed
43 | void *(*start_routine) (void *);
44 |
45 | /// Argument passed to the function
46 | void *arg;
47 |
48 | /// Result of the thread function
49 | void *result;
50 |
51 | /// Stack Base
52 | void *stackaddr;
53 |
54 | /// Stack Size
55 | size_t stacksize;
56 |
57 | /// Context of the thread
58 | sigjmp_buf context;
59 |
60 | /// Name for debugging
61 | char name[MTHREAD_TCB_NAMELEN];
62 |
63 | /// Detachment type
64 | int joinable;
65 |
66 | /// TID to be joined to once finished
67 | mthread_t joined_on;
68 |
69 | /// For signal handling
70 | sigset_t sigpending;
71 | } mthread;
72 |
73 | /// Thread Attribute Structure
74 | struct mthread_attr {
75 | /// Name for debugging
76 | char a_name[MTHREAD_TCB_NAMELEN];
77 |
78 | /// Detachment type
79 | int a_joinable;
80 |
81 | /// Stack Base
82 | void *a_stackaddr;
83 |
84 | /// Stack Size
85 | size_t a_stacksize;
86 | };
87 |
88 | /// States of a spinlock
89 | #define LOCKED (1u)
90 | #define UNLOCKED (0u)
91 |
92 | /// Spinlock structure
93 | struct mthread_spinlock {
94 | /// Value of spinlock
95 | int value;
96 | };
97 |
98 | #endif
--------------------------------------------------------------------------------
/many-one/include/utils.h:
--------------------------------------------------------------------------------
1 | #ifndef _UTILS_H_
2 | #define _UTILS_H_
3 |
4 | #include
5 |
6 | char *util_strncpy(char *dst, const char *src, size_t dst_size);
7 |
8 | #endif
--------------------------------------------------------------------------------
/many-one/run_tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo -e "\033[34m************************RUNNING ROBUST TEST*************************\033[0m"
4 | echo "./bin/robust_test"
5 | ./bin/robust_test
6 | echo ""
7 | echo ""
8 | echo -e "\033[34m*********************RUNNING DETACH STATE TEST**********************\033[0m"
9 | echo "./bin/detach_state_test"
10 | ./bin/detach_state_test
11 | echo -e "\033[33mCASE: JOINABLE threads, but don't wait\033[0m"
12 | ./bin/detach_state_test n
13 | echo ""
14 | echo ""
15 | echo -e "\033[33mCASE: JOINABLE threads, with mthread_join()\033[0m"
16 | ./bin/detach_state_test j
17 | echo ""
18 | echo ""
19 | echo -e "\033[33mCASE: DETACHED threads, and don't wait\033[0m"
20 | ./bin/detach_state_test d
21 | echo ""
22 | echo ""
23 | echo -e "\033[33mCASE: DETACHED threads, and wait 3 seconds\033[0m"
24 | ./bin/detach_state_test x
25 | echo ""
26 | echo ""
27 | echo -e "\033[34m************************RUNNING MATRIX TEST*************************\033[0m"
28 | echo "./bin/matrix_test <./data/2.txt"
29 | ./bin/matrix_test <./data/2.txt
30 | echo ""
31 | echo ""
32 | echo -e "\033[34m***********************RUNNING SPINLOCK TEST************************\033[0m"
33 | echo "./bin/spin_test 2> /dev/null"
34 | ./bin/spin_test 2> /dev/null
35 | echo ""
36 | echo -e "\033[31mTo disable debug statements, set DEBUG = 0 in Makefile"
--------------------------------------------------------------------------------
/many-one/src/attr.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file attr.c
3 | * @brief Attribute handling functions
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include "mthread.h"
13 | #include "utils.h"
14 |
15 | /**
16 | * @brief Controls the attributes depending on the operation
17 | * @param[in] cmd Get or Set the attribute
18 | * @param[in,out] a Attribute object
19 | * @param[in] op Attribute
20 | * @param[in] ap Variable argument list corresponding to attribute
21 | * @return On success, returns 0; on error, it returns an error number
22 | */
23 | static int mthread_attr_ctrl(int cmd, mthread_attr_t *a, int op, va_list ap) {
24 | if(a == NULL)
25 | return EINVAL;
26 | switch(op) {
27 | case MTHREAD_ATTR_NAME: {
28 | /* name */
29 | if(cmd == MTHREAD_ATTR_SET) {
30 | char *src, *dst;
31 | src = va_arg(ap, char *);
32 | dst = a->a_name;
33 | util_strncpy(dst, src, MTHREAD_TCB_NAMELEN);
34 | }
35 | else {
36 | char *src, **dst;
37 | src = a->a_name;
38 | dst = va_arg(ap, char **);
39 | *dst = src;
40 | }
41 | break;
42 | }
43 | case MTHREAD_ATTR_JOINABLE: {
44 | /* detachment type */
45 | int val, *src, *dst;
46 | if(cmd == MTHREAD_ATTR_SET) {
47 | src = &val;
48 | val = va_arg(ap, int);
49 | dst = &a->a_joinable;
50 | }
51 | else {
52 | src = &a->a_joinable;
53 | dst = va_arg(ap, int *);
54 | }
55 | *dst = *src;
56 | break;
57 | }
58 | case MTHREAD_ATTR_STACK_SIZE: {
59 | /* stack size */
60 | size_t val, *src, *dst;
61 | if(cmd == MTHREAD_ATTR_SET) {
62 | src = &val;
63 | val = va_arg(ap, size_t);
64 | dst = &a->a_stacksize;
65 | }
66 | else {
67 | src = &a->a_stacksize;
68 | dst = va_arg(ap, size_t *);
69 | }
70 | *dst = *src;
71 | break;
72 | }
73 | case MTHREAD_ATTR_STACK_ADDR: {
74 | /* stack address */
75 | void *val, **src, **dst;
76 | if(cmd == MTHREAD_ATTR_SET) {
77 | src = &val;
78 | val = va_arg(ap, void *);
79 | dst = &a->a_stackaddr;
80 | }
81 | else {
82 | src = &a->a_stackaddr;
83 | dst = va_arg(ap, void **);
84 | }
85 | *dst = *src;
86 | break;
87 | }
88 | default:
89 | return EINVAL;
90 | }
91 | return 0;
92 | }
93 |
94 | /**
95 | * @brief Make a new thread attributes object and initialise it
96 | * @return On success, returns pointer to attribute object;
97 | * on error, it returns NULL
98 | */
99 | mthread_attr_t *mthread_attr_new(void) {
100 | mthread_attr_t *a;
101 | a = (mthread_attr_t *) calloc(1, sizeof(mthread_attr_t));
102 | if(a == NULL) {
103 | return NULL;
104 | }
105 |
106 | mthread_attr_init(a);
107 | return a;
108 | }
109 |
110 | /**
111 | * @brief Controls the attributes depending on the operation
112 | * @param[in,out] a Attribute object to be initialised
113 | * @return On success, returns 0; on error, it returns an error number
114 | */
115 | int mthread_attr_init(mthread_attr_t *a) {
116 | if(a == NULL)
117 | return EINVAL;
118 |
119 | util_strncpy(a->a_name, "Unknown", MTHREAD_TCB_NAMELEN);
120 | a->a_joinable = 1;
121 | a->a_stacksize = 64 * 1024;
122 | a->a_stackaddr = NULL;
123 |
124 | return 0;
125 | }
126 |
127 | /**
128 | * @brief Get particular attribute from thread attribute object
129 | * @param[in] a Attribute object
130 | * @param[in] op Attribute
131 | * @param[in] ... Variable argument list corresponding to attribute
132 | * @return On success, returns 0; on error, it returns an error number
133 | */
134 | int mthread_attr_get(mthread_attr_t *a, int op, ...) {
135 | va_list ap;
136 | int ret;
137 |
138 | va_start(ap, op);
139 | ret = mthread_attr_ctrl(MTHREAD_ATTR_GET, a, op, ap);
140 | va_end(ap);
141 | return ret;
142 | }
143 |
144 | /**
145 | * @brief Set particular attribute in thread attribute object
146 | * @param[in,out] a Attribute object
147 | * @param[in] op Attribute
148 | * @param[in] ... Variable argument list corresponding to attribute
149 | * @return On success, returns 0; on error, it returns an error number
150 | */
151 | int mthread_attr_set(mthread_attr_t *a, int op, ...) {
152 | va_list ap;
153 | int ret;
154 |
155 | va_start(ap, op);
156 | ret = mthread_attr_ctrl(MTHREAD_ATTR_SET, a, op, ap);
157 | va_end(ap);
158 | return ret;
159 | }
160 |
161 | /**
162 | * @brief Destroy thread attribute
163 | * @param[in,out] a Attribute object
164 | * @return On success, returns 0; on error, it returns an error number
165 | */
166 | int mthread_attr_destroy(mthread_attr_t *a) {
167 | if(a == NULL)
168 | return EINVAL;
169 | free(a);
170 | return 0;
171 | }
--------------------------------------------------------------------------------
/many-one/src/interrupt.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file interrupt.c
3 | * @brief To handle timers
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include "interrupt.h"
11 |
12 | /**
13 | * @brief Enable interrupts
14 | * @param[in] timer Pointer to timer
15 | * @note The timer is set for TIMER nanoseconds defined in the header
16 | * @note At each expiration of the timer, a SIGALRM is sent
17 | */
18 | void interrupt_enable(mthread_timer_t *timer) {
19 | /* Enable timer (counts down in real time) */
20 | timer->it_value.tv_sec = 0;
21 | timer->it_value.tv_usec = TIMER;
22 | timer->it_interval.tv_sec = 0;
23 | timer->it_interval.tv_usec = TIMER;
24 | setitimer(ITIMER_VIRTUAL, timer, 0);
25 | }
26 |
27 | /**
28 | * @brief Disable interrupts
29 | * @param[in] timer Pointer to timer
30 | */
31 | void interrupt_disable(mthread_timer_t *timer) {
32 | /* Disable timer */
33 | timer->it_value.tv_sec = 0;
34 | timer->it_value.tv_usec = 0;
35 | timer->it_interval.tv_sec = 0;
36 | timer->it_interval.tv_usec = 0;
37 | setitimer(ITIMER_VIRTUAL, timer, 0);
38 | }
--------------------------------------------------------------------------------
/many-one/src/mthread.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file mthread.c
3 | * @brief Thread control functions
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include "mthread.h"
15 | #include "queue.h"
16 | #include "interrupt.h"
17 | #include "mangle.h"
18 | #include "stack.h"
19 | #include "utils.h"
20 |
21 | /**
22 | * @brief For debugging purposes
23 | */
24 | #ifdef DEBUG
25 | #define dprintf(fmt, ...) \
26 | do { if (DEBUG) fprintf(stderr, fmt, ##__VA_ARGS__); } while (0)
27 | #else
28 | #define dprintf(fmt, ...) ;
29 | #endif
30 |
31 | static queue *task_q; ///< Queue containing tasks for all threads
32 | static mthread *current; ///< Thread which is running
33 | static pid_t unique = 0; ///< To allocate unique Thread IDs
34 | static mthread_timer_t timer; ///< Timer for periodic SIGVTALRM signals
35 |
36 | /**
37 | * @brief Gets the next ready thread from the task_q
38 | * @return On success, pointer to the thread; on error, NULL is returned
39 | */
40 | static mthread * get_next_ready_thread(void) {
41 | mthread *runner;
42 | int i = getcount(task_q);
43 |
44 | while(i--) {
45 | runner = dequeue(task_q);
46 |
47 | switch(runner->state) {
48 | case READY:
49 | return runner;
50 | case WAITING:
51 | case FINISHED:
52 | enqueue(task_q, runner);
53 | break;
54 | case RUNNING:
55 | return NULL;
56 | }
57 | }
58 |
59 | return NULL;
60 | }
61 |
62 | /**
63 | * @brief Cleans up all malloc(3)ed and mmap(3)ed regions
64 | */
65 | static void cleanup_handler(void) {
66 | dprintf("%-15s: Cleaning up data structures\n", "cleanup_handler");
67 |
68 | mthread *t;
69 | int n = getcount(task_q);
70 | while(n--) {
71 | t = dequeue(task_q);
72 | deallocate_stack(t->stackaddr, t->stacksize);
73 | free(t);
74 | }
75 | free(task_q);
76 | }
77 |
78 | /**
79 | * @brief Wrapper around user start function
80 | * @note It makes an implicit call to mthread_exit() to exit the thread
81 | */
82 | static void mthread_start(void) {
83 | dprintf("%-15s: Entered with TID %d\n", "mthread_start", current->tid);
84 | current->result = current->start_routine(current->arg);
85 | mthread_exit(current->result);
86 | }
87 |
88 | /**
89 | * @brief Schedules next ready thread
90 | * @param[in] signum Signal number for which this function is a handler
91 | * @note All signals are blocked in the scheduler
92 | */
93 | static void scheduler(int signum) {
94 | dprintf("%-15s: SIGVTALRM received\n", "scheduler");
95 | /* Disable timer interrupts when scheduler is running */
96 | interrupt_disable(&timer);
97 |
98 | /* Save context and signal masks */
99 | if(sigsetjmp(current->context, 1) == 1)
100 | return;
101 |
102 | dprintf("%-15s: Saving context of Thread TID = %d\n", "scheduler", current->tid);
103 |
104 | /* Change state of current thread from RUNNING to READY*/
105 | if(current->state == RUNNING)
106 | current->state = READY;
107 |
108 | /* Enqueue current thread to task queue */
109 | enqueue(task_q, current);
110 |
111 | /* Get next ready thread running */
112 | current = get_next_ready_thread();
113 | if(current == NULL) {
114 | /* Exit if no threads left to schedule */
115 | exit(0);
116 | }
117 | current->state = RUNNING;
118 |
119 | /* Raise all pending signals */
120 | for(int sig = 1; sig < NSIG; sig++) {
121 | if(sigismember(¤t->sigpending, sig)) {
122 | raise(sig);
123 | sigdelset(¤t->sigpending, sig);
124 | dprintf("%-15s: Raised pending signal %d of TID = %d\n", "scheduler", sig, current->tid);
125 | }
126 | }
127 | /* Enable timer interrupts before loading next thread */
128 | interrupt_enable(&timer);
129 |
130 | dprintf("%-15s: Loading context of Thread TID = %d\n", "scheduler", current->tid);
131 | /* Load context and signal masks */
132 | siglongjmp(current->context, 1);
133 | }
134 |
135 | /**
136 | * @brief Initialise the mthread library
137 | * @note It has to be the first mthread API function call in an application,
138 | * and is mandatory.
139 | * @return On success, returns 0; on error, it returns an error number
140 | */
141 | int mthread_init(void) {
142 | dprintf("%-15s: Started\n", "mthread_init");
143 |
144 | /* Initialise queues */
145 | task_q = calloc(1, sizeof(queue));
146 | initialize(task_q);
147 |
148 | /* Register cleanup handler to be called on exit */
149 | atexit(cleanup_handler);
150 |
151 | /* Make thread control block for main thread */
152 | current = (mthread *) calloc(1, sizeof(mthread));
153 | current->tid = unique++;
154 | current->state = RUNNING;
155 | current->joined_on = -1;
156 | current->start_routine = current->arg = current->result = NULL;
157 |
158 | /* Setting up signal handler */
159 | struct sigaction setup_action;
160 | sigset_t block_mask;
161 | sigfillset(&block_mask);
162 | setup_action.sa_handler = scheduler;
163 | setup_action.sa_mask = block_mask;
164 | setup_action.sa_flags = 0;
165 | sigaction(SIGVTALRM, &setup_action, NULL);
166 |
167 | /* Setup timer for regular interrupts */
168 | interrupt_enable(&timer);
169 |
170 | dprintf("%-15s: Exited\n", "mthread_init");
171 | return 0;
172 | }
173 |
174 | /**
175 | * @brief Create a new thread
176 | * @param[in] thread Pointer to thread handle
177 | * @param[in] attr Pointer to attribute object
178 | * @param[in] start_routine Start function of the thread
179 | * @param[in] arg Arguments to be passed to the start function
180 | * @return On success, returns 0; on error, it returns an error number
181 | */
182 | int mthread_create(mthread_t *thread, const mthread_attr_t *attr, void *(*start_routine)(void *), void *arg) {
183 | dprintf("%-15s: Started\n", "mthread_create");
184 |
185 | if(thread == NULL)
186 | return EFAULT;
187 |
188 | if(start_routine == NULL)
189 | return EFAULT;
190 |
191 | if(unique == MTHREAD_MAX_THREADS)
192 | return EAGAIN;
193 |
194 | mthread *tmp = (mthread *) calloc(1, sizeof(mthread));
195 | if(tmp == NULL)
196 | return EAGAIN;
197 |
198 | interrupt_disable(&timer);
199 |
200 | tmp->tid = unique++;
201 | tmp->state = READY;
202 | tmp->start_routine = start_routine;
203 | tmp->arg = arg;
204 | tmp->joined_on = -1;
205 | sigemptyset(&tmp->sigpending);
206 |
207 | /* Stack handling */
208 | if(attr != NULL && attr->a_stacksize > MTHREAD_MIN_STACK)
209 | tmp->stacksize = attr->a_stacksize;
210 | else
211 | tmp->stacksize = MTHREAD_MIN_STACK;
212 |
213 | tmp->stackaddr = (attr == NULL ? NULL : attr->a_stackaddr);
214 | if(tmp->stackaddr == NULL) {
215 | tmp->stackaddr = allocate_stack(tmp->stacksize);
216 | if(tmp->stackaddr == NULL) {
217 | interrupt_enable(&timer);
218 | return EAGAIN;
219 | }
220 | }
221 |
222 | /* Configure remaining attributes */
223 | if(attr != NULL) {
224 | /* Overtake fields from the attribute structure */
225 | tmp->joinable = attr->a_joinable;
226 | util_strncpy(tmp->name, attr->a_name, MTHREAD_TCB_NAMELEN);
227 | }
228 | else {
229 | /* Set defaults */
230 | tmp->joinable = TRUE;
231 | snprintf(tmp->name, MTHREAD_TCB_NAMELEN, "User%d", tmp->tid);
232 | }
233 |
234 | /* Make context for new thread */
235 | sigsetjmp(tmp->context, 1);
236 |
237 | /* Change stack pointer to point to top of stack */
238 | tmp->context[0].__jmpbuf[JB_SP] = mangle((long int) tmp->stackaddr + tmp->stacksize - sizeof(long int));
239 |
240 | /* Change program counter to point to start function */
241 | tmp->context[0].__jmpbuf[JB_PC] = mangle((long int) mthread_start);
242 |
243 | enqueue(task_q, tmp);
244 | *thread = tmp->tid;
245 |
246 | interrupt_enable(&timer);
247 | dprintf("%-15s: Created Thread with TID = %d and put in task queue\n", "mthread_create", tmp->tid);
248 | return 0;
249 | }
250 |
251 | /**
252 | * @brief Join with a terminated thread
253 | * @param[in] tid Handle of thread to wait for
254 | * @param[in] retval To save the exit status of the target thread
255 | * @return On success, returns 0; on error, it returns an error number
256 | */
257 | int mthread_join(mthread_t tid, void **retval) {
258 | dprintf("%-15s: Thread TID = %d wants to wait on TID = %d\n", "mthread_join", current->tid, tid);
259 |
260 | interrupt_disable(&timer);
261 | mthread *target = search_on_tid(task_q, tid);
262 |
263 | /* Deadlock check */
264 | if(current->tid == tid) {
265 | interrupt_enable(&timer);
266 | return EDEADLK;
267 | }
268 |
269 | /* Thread exists check */
270 | if(target == NULL) {
271 | interrupt_enable(&timer);
272 | return ESRCH;
273 | }
274 |
275 | /* Thread is joinable and no one has joined on it check */
276 | if(!target->joinable || target->joined_on != -1) {
277 | interrupt_enable(&timer);
278 | return EINVAL;
279 | }
280 |
281 | target->joined_on = current->tid;
282 | current->state = WAITING;
283 | interrupt_enable(&timer);
284 |
285 | while(target->state != FINISHED);
286 |
287 | if(retval) {
288 | *retval = target->result;
289 | }
290 |
291 | dprintf("%-15s: Exited\n", "mthread_join");
292 | return 0;
293 | }
294 |
295 | /**
296 | * @brief Terminate calling thread
297 | * @param[in] retval Return value of the thread
298 | * @return Does not return to the caller
299 | * @note Performing a return from the start funciton of any thread results in
300 | * an implicit call to mthread_exit()
301 | */
302 | void mthread_exit(void *retval) {
303 | dprintf("%-15s: TID %d exiting\n", "mthread_exit", current->tid);
304 | interrupt_disable(&timer);
305 |
306 | current->state = FINISHED;
307 | current->result = retval;
308 |
309 | if(current->joined_on != -1) {
310 | mthread *target = search_on_tid(task_q, current->joined_on);
311 | target->state = READY;
312 | }
313 |
314 | interrupt_enable(&timer);
315 | mthread_yield();
316 | }
317 |
318 | /**
319 | * @brief Yield the processor
320 | */
321 | void mthread_yield(void) {
322 | dprintf("%-15s: Yielding to next thread\n", "mthread_yield");
323 | raise(SIGVTALRM);
324 | }
325 |
326 | /**
327 | * @brief Send a signal to a thread
328 | * @param[in] thread Thread handle of thread to which signal needs to be sent
329 | * @param[in] sig Signal number corresponding to signal
330 | * @return On success, returns 0; on error, it returns an error number
331 | */
332 | int mthread_kill(mthread_t thread, int sig) {
333 | dprintf("%-15s: Started\n", "mthread_kill");
334 | if(sig < 0 || sig > NSIG)
335 | return EINVAL;
336 |
337 | if(thread == current->tid) {
338 | dprintf("%-15s: Raised signal %d for tid %d\n", "mthread_kill", sig, current->tid);
339 | return raise(sig);
340 | }
341 |
342 | interrupt_disable(&timer);
343 | mthread *target = search_on_tid(task_q, thread);
344 | if(target == NULL) {
345 | interrupt_enable(&timer);
346 | return EINVAL;
347 | }
348 |
349 | sigaddset(&target->sigpending, sig);
350 |
351 | dprintf("%-15s: Added signal %d to pending signals of TID %d\n", "mthread_kill", sig, target->tid);
352 | dprintf("%-15s: Exited\n", "mthread_kill");
353 | interrupt_enable(&timer);
354 | return 0;
355 | }
356 |
357 | /**
358 | * @brief Detach a thread
359 | * @param[in] thread Thread handle of thread to be detached
360 | * @return On success, returns 0; on error, it returns an error number
361 | * @note Once a thread has been detached, it can't be joined with
362 | * mthread_join() or be made joinable again.
363 | */
364 | int mthread_detach(mthread_t thread) {
365 | interrupt_disable(&timer);
366 | mthread *target = search_on_tid(task_q, thread);
367 |
368 | if(target == NULL) {
369 | interrupt_enable(&timer);
370 | return ESRCH;
371 | }
372 |
373 | if(target->joined_on != -1) {
374 | interrupt_enable(&timer);
375 | return EINVAL;
376 | }
377 |
378 | target->joinable = FALSE;
379 | dprintf("%-15s: Marked TID %d as detached\n", "mthread_detach", thread);
380 |
381 | interrupt_enable(&timer);
382 | return 0;
383 | }
384 |
385 | /**
386 | * @brief Compare Thread IDs
387 | * @param[in] t1 Thread handle of thread 1
388 | * @param[in] t2 Thread handle of thread 2
389 | * @return 0 on success, and non-zero on failure
390 | */
391 | int mthread_equal(mthread_t t1, mthread_t t2) {
392 | return t1 - t2;
393 | }
--------------------------------------------------------------------------------
/many-one/src/queue.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file queue.c
3 | * @brief Singly linked queue for thread control blocks
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include "queue.h"
12 |
13 | /**
14 | * @brief Initialise the queue
15 | * @param[in] q Pointer to queue
16 | */
17 | void initialize(queue *q) {
18 | q->count = 0;
19 | q->head = NULL;
20 | q->tail = NULL;
21 | }
22 |
23 | /**
24 | * @brief Check if queue is empty
25 | * @param[in] q Pointer to queue
26 | * @return If empty, returns 1; else 0
27 | */
28 | int isempty(queue *q) {
29 | if(q->head == NULL) {
30 | assert(q->count == 0);
31 | assert(q->tail == 0);
32 | }
33 | return (q->head == NULL);
34 | }
35 |
36 | /**
37 | * @brief Enqueue a TCB in the queue
38 | * @param[in] q Pointer to queue
39 | * @param[in] thd Pointer to TCB
40 | */
41 | void enqueue(queue *q, mthread *thd) {
42 | node *tmp = calloc(1, sizeof(node));
43 | tmp->thd = thd;
44 | tmp->next = NULL;
45 |
46 | if(isempty(q)) {
47 | q->head = q->tail = tmp;
48 | }
49 | else {
50 | q->tail->next = tmp;
51 | q->tail = tmp;
52 | }
53 | q->count++;
54 |
55 | return;
56 | }
57 |
58 | /**
59 | * @brief Dequeue a TCB in the queue
60 | * @param[in] q Pointer to queue
61 | * @return Pointer to TCB dequeued; Return NULL if empty
62 | */
63 | mthread *dequeue(queue *q) {
64 | if(isempty(q))
65 | return NULL;
66 |
67 | node *tmp = q->head;
68 | mthread *n = q->head->thd;
69 |
70 | q->head = q->head->next;
71 | q->count--;
72 |
73 | if(q->head == NULL) {
74 | q->tail = NULL;
75 | }
76 |
77 | free(tmp);
78 | return(n);
79 | }
80 |
81 | /**
82 | * @brief Get count of TCBs in queue
83 | * @param[in] q Pointer to queue
84 | * @return Count
85 | */
86 | int getcount(queue *q) {
87 | return q->count;
88 | }
89 |
90 | /**
91 | * @brief Display TCBs in queue
92 | * @param[in] q Pointer to queue
93 | */
94 | void display(queue *q) {
95 | if(isempty(q))
96 | return;
97 |
98 | node *runner = q->head;
99 | printf("Queue (%d): ", q->count);
100 | while(runner) {
101 | printf("%d ", runner->thd->tid);
102 | runner = runner->next;
103 | }
104 | printf("\n");
105 | }
106 |
107 | /**
108 | * @brief Search for a TCB based on TID in the queue
109 | * @param[in] q Pointer to queue
110 | * @param[in] tid TID of the target thread
111 | * @return Pointer to target thread; Return NULL if empty
112 | */
113 | mthread *search_on_tid(queue *q, pid_t tid) {
114 | if(isempty(q))
115 | return NULL;
116 |
117 | node *runner = q->head;
118 | while(runner) {
119 | if (runner->thd->tid == tid) {
120 | return runner->thd;
121 | }
122 | runner = runner->next;
123 | }
124 | return NULL;
125 | }
126 |
127 | /**
128 | * @brief Destroy the queue
129 | * @param[in] q Pointer to queue
130 | */
131 | void destroy(queue *q) {
132 | if(isempty(q))
133 | return;
134 |
135 | node *curr = q->head, *next;
136 | for(int i = 0; i < q->count; i++) {
137 | next = curr->next;
138 | free(curr->thd);
139 | free(curr);
140 | curr = next;
141 | }
142 |
143 | return;
144 | }
--------------------------------------------------------------------------------
/many-one/src/spin_lock.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file spin_lock.c
3 | * @brief Spinlock synchronisation primitive
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include "mthread.h"
12 |
13 | /**
14 | * @brief Atomic Compare and Swap
15 | * @param[in,out] lock_addr Pointer to lock
16 | * @param[in] expected Expected value of lock
17 | * @param[in] desirec Desired value of lock
18 | * @return Upon success, the macro returns true. Upon failure, the desired
19 | * value is overwritten with the value of the atomic variable and false is
20 | * returned.
21 | */
22 | static inline int atomic_cas(int *lock_addr, int expected, int desired) {
23 | return atomic_compare_exchange_strong(lock_addr, &expected, desired);
24 | }
25 |
26 | /**
27 | * @brief Initialise the spinlock
28 | * @param[out] lock Pointer to the spinlock
29 | * @note Reinitialization of a lock held by other threads may lead to
30 | * unexpected results, hence this function must be called only once
31 | * @return On success, returns 0; on error, it returns an error number
32 | */
33 | int mthread_spin_init(mthread_spinlock_t *lock) {
34 | assert(lock);
35 | lock->value = UNLOCKED;
36 | return 0;
37 | }
38 |
39 | /**
40 | * @brief Lock a spinlock
41 | * @param[in,out] lock Pointer to the spinlock
42 | * @note The call is blocking and will return only if the lock is acquired
43 | * @return On success, returns 0; on error, it returns an error number
44 | */
45 | int mthread_spin_lock(mthread_spinlock_t *lock) {
46 | assert(lock);
47 | while (!atomic_cas(&lock->value, UNLOCKED, LOCKED));
48 | return 0;
49 | }
50 |
51 | /**
52 | * @brief Try locking a spinlock
53 | * @param[in,out] lock Pointer to the spinlock
54 | * @note The call returns immediately if acquiring lock fails
55 | * @return On success, returns 0; on error, it returns an error number
56 | */
57 | int mthread_spin_trylock(mthread_spinlock_t *lock) {
58 | assert(lock);
59 | if(atomic_cas(&lock->value, UNLOCKED, LOCKED))
60 | return 0;
61 |
62 | return EBUSY;
63 | }
64 |
65 | /**
66 | * @brief Unlock a spinlock
67 | * @param[in,out] lock Pointer to the spinlock
68 | * @note Calling mthread_spin_unlock() on a lock that is not held by the
69 | * caller results in undefined behavior.
70 | * @return On success, returns 0; on error, it returns an error number
71 | */
72 | int mthread_spin_unlock(mthread_spinlock_t *lock) {
73 | assert(lock);
74 | atomic_cas(&lock->value, LOCKED, UNLOCKED);
75 | return 0;
76 | }
--------------------------------------------------------------------------------
/many-one/src/stack.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file stack.c
3 | * @brief Thread stack allocation and deallocation functions
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include "stack.h"
13 |
14 | /**
15 | * @brief Get the stack size of a thread
16 | * @return Size in bytes
17 | */
18 | size_t get_stack_size(void) {
19 | struct rlimit limit;
20 | getrlimit(RLIMIT_STACK, &limit);
21 | return limit.rlim_cur;
22 | }
23 |
24 | /**
25 | * @brief Get the page size of a thread
26 | * @return Size in bytes
27 | */
28 | static size_t get_page_size(void) {
29 | return sysconf(_SC_PAGESIZE);
30 | }
31 |
32 | /**
33 | * @brief Allocate a stack
34 | * @param[in] stack_size Size of stack to mmap
35 | * @return Pointer to the base of the stack
36 | */
37 | void * allocate_stack(size_t stack_size) {
38 | size_t page_size = get_page_size();
39 |
40 | void *base = mmap(NULL,
41 | stack_size + page_size,
42 | PROT_READ | PROT_WRITE,
43 | MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
44 | -1,
45 | 0);
46 | if(base == MAP_FAILED)
47 | return NULL;
48 |
49 | if(mprotect(base, page_size, PROT_NONE) == -1) {
50 | munmap(base, stack_size + page_size);
51 | return NULL;
52 | }
53 |
54 | return base + page_size;
55 | }
56 |
57 | /**
58 | * @brief Deallocate a stack
59 | * @param[in] base Base of the stack
60 | * @param[in] stack_size Size of stack to mmap
61 | * @return On success, returns 0; On error, returns -1
62 | */
63 | int deallocate_stack(void *base, size_t stack_size) {
64 | size_t page_size = get_page_size();
65 | return munmap(base - page_size, stack_size + page_size);
66 | }
--------------------------------------------------------------------------------
/many-one/src/utils.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file utils.c
3 | * @brief Utility functions
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include "utils.h"
9 |
10 | /**
11 | * @brief Copy a string of length atmost n bytes including '\0' character
12 | * @param[in,out] dst String to be copied into
13 | * @param[in] src String to be copied from
14 | * @param[in] dst_size Number of characters to copy
15 | * @return Pointer to first character of destination string
16 | */
17 | char *util_strncpy(char *dst, const char *src, size_t dst_size) {
18 | if(dst_size == 0)
19 | return dst;
20 |
21 | char *d = dst;
22 | char *end = dst + dst_size - 1;
23 |
24 | while(d < end) {
25 | if((*d = *src) == '\0')
26 | return dst;
27 | d++;
28 | src++;
29 | }
30 | *d = '\0';
31 |
32 | return dst;
33 | }
--------------------------------------------------------------------------------
/many-one/test/detach_state_test.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Example of thread creation and termination
3 | * This is a example to illustrate how execution times are affected
4 | * by true parallelism versus interleaved execution.
5 | * The behavior depends on the first argument.
6 | * See function usage() for details.
7 | */
8 |
9 | #define _XOPEN_SOURCE 500
10 | #define _REENTRANT
11 | #include "mthread.h"
12 | #include
13 | #include
14 | #include
15 | #include
16 | #include
17 | #include
18 | #include
19 |
20 | #define MCHECK(FCALL) \
21 | { \
22 | int result; \
23 | if ((result = (FCALL)) != 0) { \
24 | fprintf(stderr, "FATAL: %s (%s)", strerror(result), #FCALL); \
25 | exit(-1); \
26 | } \
27 | }
28 |
29 | #define NTHREADS 5
30 | #define NITERATIONS 1000000
31 |
32 | int idx[NTHREADS];
33 | clock_t start, end;
34 |
35 | void *func(void *arg)
36 | {
37 | int *idx = (int *)arg;
38 | fprintf(stderr, "Thread %d started\n", *idx);
39 |
40 | /**
41 | * The following is to keep the CPU busy for a fixed amount
42 | * of work, so we can compare how long it takes with several
43 | * threads versus a single thread
44 | */
45 | for (long int k = 0; k < NITERATIONS; k++) {
46 | continue;
47 | }
48 | end = clock();
49 |
50 | fprintf(stderr, "Thread %d exited\n", *idx);
51 |
52 | *idx = *idx * 10;
53 | return (void *)*idx;
54 | }
55 |
56 | void usage()
57 | {
58 | fprintf(stderr, "Usage: detach_state_test [ n | x | j | d ]\n"
59 | "n : JOINABLE threads, but don't wait\n"
60 | "j : JOINABLE threads, with mthread_join()\n"
61 | "d : DETACHED threads, and don't wait\n"
62 | "x : DETACHED threads, and wait 3 seconds\n");
63 | }
64 |
65 | int main(int argc, char **argv)
66 | {
67 | int i;
68 | double elapsed_time = 0;
69 | mthread_attr_t attrs;
70 | mthread_t thread[NTHREADS];
71 | void *value_ptr;
72 |
73 | if (argc != 2) {
74 | usage();
75 | exit(-1);
76 | }
77 | printf("----------------------------------------------\n");
78 | printf("Understanding Thread States \n");
79 | printf("----------------------------------------------\n");
80 |
81 | start = clock();
82 | for (long int k = 0; k < NITERATIONS; k++) {
83 | continue;
84 | }
85 | end = clock();
86 |
87 | /* Time elapsed in seconds */
88 | elapsed_time = (end - start) / (double)CLOCKS_PER_SEC;
89 | fprintf(stderr, "Time taken for one loop = %f seconds\n", elapsed_time);
90 |
91 | mthread_init();
92 | mthread_attr_init(&attrs);
93 |
94 | /**
95 | * Use the command-line argument to decide whether to create
96 | * the threads detached or joinable
97 | */
98 | if ((strcmp(argv[1], "d") == 0) || (strcmp(argv[1], "x") == 0)) {
99 | MCHECK(mthread_attr_set(&attrs, MTHREAD_ATTR_JOINABLE, JOINABLE));
100 | }
101 |
102 | /* Create threads */
103 | for (i = 0; i < NTHREADS; i++) {
104 | idx[i] = i;
105 | MCHECK(mthread_create(&thread[i], &attrs, func, (void *)&idx[i]));
106 | fprintf(stderr, "Thread %d created\n", i);
107 | }
108 |
109 |
110 | /* Wait for the threads to complete */
111 | if (strcmp(argv[1], "j") == 0) {
112 | for (i = 0; i < NTHREADS; i++) {
113 | MCHECK(mthread_join(thread[i], &value_ptr));
114 | fprintf(stderr, "Thread %d returned value %d\n", i, (int)value_ptr);
115 | }
116 | }
117 |
118 | /* Find out how long the computation took */
119 | end = clock();
120 |
121 | if (strcmp(argv[1], "x") == 0) {
122 | fprintf(stderr, "Main thread waiting 3 seconds\n");
123 | sleep(3);
124 | }
125 |
126 | elapsed_time = (end - start) / (double)CLOCKS_PER_SEC;
127 |
128 | fprintf(stderr, "Time taken by all %d threads = %f seconds\n", NTHREADS, elapsed_time);
129 |
130 | fprintf(stderr, "Main thread exiting\n");
131 |
132 | printf("----------------------------------------------\n");
133 |
134 | return 0;
135 | }
136 |
--------------------------------------------------------------------------------
/many-one/test/matrix_test.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Matrix multiplication using three threads using
3 | * data parralelism.
4 | * Input is STDIN
5 | * Input files are available in ../data
6 | * Namely 1.txt 2.txt 3.txt
7 | * Output is on STDOUT
8 | */
9 |
10 | #include "mthread.h"
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 |
17 | #define MCHECK(FCALL) \
18 | { \
19 | int result; \
20 | if ((result = (FCALL)) != 0) { \
21 | fprintf(stderr, "FATAL: %s (%s)", strerror(result), #FCALL); \
22 | exit(-1); \
23 | } \
24 | }
25 |
26 | /* Number of threads to use */
27 | #define NUM_OF_THREADS 3
28 |
29 | /* Structure to define a matrix */
30 | typedef struct {
31 | int **a;
32 | int rows;
33 | int cols;
34 | }matrix;
35 |
36 | /* Global matrices to allow easier threading */
37 | matrix a, b, c;
38 |
39 | int running = 1;
40 |
41 | /**
42 | * Initialise the matrix
43 | * @param m pointer to matrix
44 | */
45 | void initMatrix(matrix *m) {
46 | m->a = (int **)malloc(sizeof(int *) * m->rows);
47 |
48 | for(int i = 0; i < m->rows; i++)
49 | m->a[i] = (int *)malloc(sizeof(int) * m->cols);
50 |
51 | for(int i = 0; i < m->rows; i++)
52 | for(int j = 0; j < m->cols; j++)
53 | m->a[i][j] = 0;
54 | }
55 |
56 | /**
57 | * Build matrix from STDIN
58 | * Assume matrix is not initialised
59 | * @param m pointer to matrix
60 | */
61 | void buildMatrix(matrix *m) {
62 | initMatrix(m);
63 |
64 | for(int i = 0; i < m->rows; i++) {
65 | for(int j = 0; j < m->cols; j++) {
66 | fscanf(stdin, "%d", &(m->a[i][j]));
67 | }
68 | }
69 | }
70 |
71 | /**
72 | * Print matrix on STDOUT
73 | * @param m matrix to be printed
74 | */
75 | void printMatrix(matrix m) {
76 | for(int i = 0; i < m.rows; i++) {
77 | for(int j = 0; j < m.cols; j++) {
78 | fprintf(stdout, "%d ", m.a[i][j]);
79 | }
80 | fprintf(stdout, "\n");
81 | }
82 | }
83 |
84 | /**
85 | * Frees memory allocated
86 | * @param m pointer to matrix
87 | */
88 | void freeMatrix(matrix *m) {
89 | for(int i = 0; i < m->rows; i++) {
90 | free(m->a[i]);
91 | }
92 | free(m->a);
93 | }
94 |
95 | /**
96 | * Multiply two matrices
97 | * @param arg an integer array having details about the thread's rows of interest
98 | */
99 | void * multiplyMatrix(void *arg) {
100 | int i, j, k, sum;
101 | int *t = (int *)arg;
102 | int rowStart = t[0];
103 | int rowEnd = t[1];
104 |
105 | // printf("Thread %d:\trowStart %d\trowEnd %d\tcols %d\n", t[3], rowStart, rowEnd, cols);
106 |
107 | for(i = rowStart; i < rowEnd; i++) {
108 | for(j = 0; j < c.cols; j++) {
109 | sum = 0;
110 | for(k = 0; k < a.cols; k++) {
111 | sum += a.a[i][k] * b.a[k][j];
112 | }
113 | c.a[i][j] = sum;
114 | }
115 | }
116 |
117 | mthread_exit(NULL);
118 | }
119 |
120 | int main() {
121 | int i, d[NUM_OF_THREADS][2];
122 |
123 | /* Initialise first matrix */
124 | fscanf(stdin, "%d %d", &(a.rows), &(a.cols));
125 | buildMatrix(&a);
126 |
127 | /* Initialise second matrix */
128 | fscanf(stdin, "%d %d", &(b.rows), &(b.cols));
129 | buildMatrix(&b);
130 |
131 | /* Set result matrix rows and cols */
132 | c.rows = a.rows;
133 | c.cols = b.cols;
134 |
135 | /* Initialise the result matrix */
136 | initMatrix(&c);
137 |
138 | /* Thread identifiers */
139 | mthread_t tid[NUM_OF_THREADS];
140 |
141 | MCHECK(mthread_init());
142 |
143 | for (i = 0; i < NUM_OF_THREADS; i++) {
144 | /* Calculate starting row thread should start process */
145 | d[i][0] = ceil(i * (double)(c.rows)/NUM_OF_THREADS);
146 |
147 | /* Calculate ending row thread should start process */
148 | d[i][1] = ceil((i + 1) * (double)(c.rows)/NUM_OF_THREADS);
149 |
150 | /* Create thread and pass args */
151 | MCHECK(mthread_create(&tid[i], NULL, multiplyMatrix, d[i]));
152 | }
153 |
154 | /* Wait until all threads complete */
155 | for(i = 0; i < NUM_OF_THREADS; i++) {
156 | MCHECK(mthread_join(tid[i], NULL));
157 | }
158 |
159 | printMatrix(c);
160 |
161 | /* Free all allocated memory */
162 | freeMatrix(&a);
163 | freeMatrix(&b);
164 | freeMatrix(&c);
165 | return 0;
166 | }
--------------------------------------------------------------------------------
/many-one/test/robust_test.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Unit testing for public API functions provided by the library
3 | */
4 |
5 | #define _REENTRANT
6 | #include "mthread.h"
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 |
13 | #define NTHREADS 5
14 |
15 | #define print(str) write(STDOUT_FILENO, str, strlen(str))
16 |
17 | #define MCHECKPASS(FCALL) \
18 | { \
19 | int result; \
20 | if ((result = (FCALL)) != 0) \
21 | { \
22 | fprintf(stderr, "FATAL: %s (%s)\n", strerror(result), #FCALL); \
23 | fprintf(stdout, "TEST FAILED\n\n"); \
24 | exit(EXIT_FAILURE); \
25 | } \
26 | else \
27 | { \
28 | fprintf(stdout, "TEST PASSED\n\n"); \
29 | } \
30 | }
31 |
32 | #define MCHECKFAIL(FCALL) \
33 | { \
34 | int result; \
35 | if ((result = (FCALL)) != 0) \
36 | { \
37 | fprintf(stderr, "FATAL: %s (%s)\n", strerror(result), #FCALL); \
38 | fprintf(stdout, "TEST PASSED\n\n"); \
39 | } \
40 | else \
41 | { \
42 | fprintf(stdout, "TEST FAILED\n\n"); \
43 | exit(EXIT_FAILURE); \
44 | } \
45 | }
46 |
47 | #define MCHECK(FCALL) \
48 | { \
49 | int result; \
50 | if ((result = (FCALL)) != 0) \
51 | { \
52 | fprintf(stderr, "FATAL: %s (%s)\n", strerror(result), #FCALL); \
53 | } \
54 | }
55 |
56 | int running, count;
57 |
58 | void handler(int sig) {
59 | print("Inside the handler\n");
60 | running = 0;
61 | }
62 |
63 | void *thread1(void *arg) {
64 | printf("In thread 1\n");
65 | mthread_exit((void *)64);
66 | }
67 |
68 | void *thread2(void *arg) {
69 | printf("In thread 2\n");
70 | return (void *)2;
71 | }
72 |
73 | void *infinite(void *arg) {
74 | printf("In thread having infinite while loop\n");
75 | while(running);
76 | return (void *)128;
77 | }
78 | void* threadone(void *args) {
79 | count++;
80 | }
81 |
82 | void* threadtwo(void *args) {
83 | mthread_t tid;
84 | mthread_create(&tid, NULL, threadone, NULL);
85 | mthread_join(tid, NULL);
86 | count++;
87 | }
88 |
89 | void* threadthree(void *args) {
90 | return (void *)1;
91 | }
92 |
93 | void* keep_going(void *args) {
94 | for (long long int i = 0; i < 10000000; i++);
95 | }
96 |
97 |
98 | int main(int argc, char **argv) {
99 | mthread_init();
100 |
101 | printf("-------------------------------------------\n");
102 | printf("Thread Attribute Handling\n");
103 | printf("-------------------------------------------\n");
104 | printf("1] Handling detach state of a thread\n");
105 | {
106 | int join;
107 | mthread_attr_t *attr = mthread_attr_new();
108 | MCHECK(mthread_attr_get(attr, MTHREAD_ATTR_JOINABLE, &join));
109 | printf("Detach State: Expected 1 Actual %d\n", join);
110 | MCHECK(mthread_attr_set(attr, MTHREAD_ATTR_JOINABLE, DETACHED));
111 | MCHECK(mthread_attr_get(attr, MTHREAD_ATTR_JOINABLE, &join));
112 | printf("Detach State: Expected 0 Actual %d\n", join);
113 | MCHECK(mthread_attr_destroy(attr));
114 | printf("TEST PASSED\n\n");
115 | }
116 |
117 | printf("2] Handling stack of a thread\n");
118 | {
119 | size_t s;
120 | void *t;
121 | void *stack = malloc(10 * 1024);
122 | mthread_attr_t *attr = mthread_attr_new();
123 | MCHECK(mthread_attr_get(attr, MTHREAD_ATTR_STACK_SIZE, &s));
124 | MCHECK(mthread_attr_get(attr, MTHREAD_ATTR_STACK_ADDR, &t));
125 | printf("Default stack size = %lu\n", s);
126 | printf("Default stack address = %p\n", t);
127 |
128 | MCHECK(mthread_attr_set(attr, MTHREAD_ATTR_STACK_SIZE, 10 * 1024));
129 | MCHECK(mthread_attr_set(attr, MTHREAD_ATTR_STACK_ADDR, stack));
130 | printf("Set stack size = 10240\n");
131 | printf("Set stack address = %p\n", stack);
132 |
133 | MCHECK(mthread_attr_get(attr, MTHREAD_ATTR_STACK_SIZE, &s));
134 | MCHECK(mthread_attr_get(attr, MTHREAD_ATTR_STACK_ADDR, &t));
135 | printf("New stack size = %lu\n", s);
136 | printf("New stack address = %p\n", t);
137 |
138 | MCHECK(mthread_attr_destroy(attr));
139 | if(s == 10240 && t == stack) {
140 | printf("TEST PASSED\n\n");
141 | }
142 | else {
143 | printf("TEST FAILED\n\n");
144 | exit(EXIT_FAILURE);
145 | }
146 | }
147 |
148 | printf("-------------------------------------------\n");
149 | printf("Thread Create\n");
150 | printf("-------------------------------------------\n");
151 | printf("1] Start Routine is NULL\n");
152 | {
153 | mthread_t tid;
154 | MCHECKFAIL(mthread_create(&tid, NULL, NULL, NULL));
155 | }
156 |
157 | printf("2] Create Thread with Default Attributes\n");
158 | {
159 | mthread_t tid;
160 | MCHECK(mthread_create(&tid, NULL, thread1, NULL));
161 | MCHECK(mthread_join(tid, NULL));
162 | fprintf(stdout, "TEST PASSED\n\n");
163 | }
164 |
165 | printf("3] Create Detached Thread\n");
166 | {
167 | mthread_t tid;
168 | mthread_attr_t attr;
169 | mthread_attr_init(&attr);
170 | mthread_attr_set(&attr, MTHREAD_ATTR_JOINABLE, DETACHED);
171 | MCHECK(mthread_create(&tid, &attr, thread1, NULL));
172 | MCHECKFAIL(mthread_join(tid, NULL));
173 | }
174 |
175 | printf("4] Create Thread having Stack Size of 10KB\n");
176 | {
177 | mthread_t tid;
178 | mthread_attr_t attr;
179 | mthread_attr_init(&attr);
180 | mthread_attr_set(&attr, MTHREAD_ATTR_STACK_SIZE, 10 * 1024);
181 | void *stack = malloc(10 * 1024);
182 | mthread_attr_set(&attr, MTHREAD_ATTR_STACK_ADDR, stack);
183 | MCHECK(mthread_create(&tid, &attr, thread1, NULL));
184 | MCHECK(mthread_join(tid, NULL));
185 | fprintf(stdout, "TEST PASSED\n\n");
186 | }
187 |
188 | printf("-------------------------------------------\n");
189 | printf("Thread Join\n");
190 | printf("-------------------------------------------\n");
191 | printf("1] Invalid Thread Handle Passed\n");
192 | {
193 | mthread_t tid;
194 | MCHECK(mthread_create(&tid, NULL, thread1, NULL));
195 | MCHECKFAIL(mthread_join(1000, NULL));
196 | }
197 |
198 | printf("2] Joining on a detached thread\n");
199 | {
200 | mthread_t tid;
201 | mthread_attr_t attr;
202 | mthread_attr_init(&attr);
203 | mthread_attr_set(&attr, MTHREAD_ATTR_JOINABLE, DETACHED);
204 | MCHECK(mthread_create(&tid, &attr, thread1, NULL));
205 | MCHECKFAIL(mthread_join(tid, NULL));
206 | }
207 |
208 | printf("3] Joining on an already joined thread\n");
209 | {
210 | mthread_t tid;
211 | MCHECK(mthread_create(&tid, NULL, thread1, NULL));
212 | MCHECK(mthread_join(tid, NULL));
213 | MCHECKFAIL(mthread_join(tid, NULL));
214 | }
215 |
216 | printf("4] Joining on a thread and collecting exit status\n");
217 | {
218 | void *value;
219 | mthread_t tid;
220 | MCHECK(mthread_create(&tid, NULL, thread1, NULL));
221 | MCHECK(mthread_join(tid, &value));
222 | fprintf(stdout, "Expected Exit Status is %d\n", 64);
223 | fprintf(stdout, "Actual Exit Status is %d\n", (int) value);
224 | if((int)value == 64) {
225 | fprintf(stdout, "TEST PASSED\n\n");
226 | }
227 | else {
228 | fprintf(stdout, "TEST FAILED\n\n");
229 | exit(EXIT_FAILURE);
230 | }
231 | }
232 |
233 | printf("5] Joining on more than one thread\n");
234 | {
235 | mthread_t tid[5];
236 | for(int i = 0; i < 5; i++) {
237 | MCHECK(mthread_create(&tid[i], NULL, thread1, NULL));
238 | fprintf(stdout, "Thread %d created\n", i);
239 | }
240 | for(int i = 0; i < 5; i++) {
241 | MCHECK(mthread_join(tid[i], NULL));
242 | fprintf(stdout, "Thread %d joined\n", i);
243 | }
244 | fprintf(stdout, "TEST PASSED\n\n");
245 | }
246 |
247 | printf("-------------------------------------------\n");
248 | printf("Thread Kill\n");
249 | printf("-------------------------------------------\n");
250 | printf("1] Send invalid signal\n");
251 | {
252 | mthread_t tid;
253 | signal(SIGUSR1, handler);
254 | running = 1;
255 | MCHECK(mthread_create(&tid, NULL, infinite, NULL));
256 | MCHECK(mthread_kill(tid, -1));
257 | running = 0;
258 | MCHECK(mthread_join(tid, NULL));
259 | fprintf(stdout, "TEST PASSED\n\n");
260 | }
261 |
262 | printf("2] Send signal to a thread\n");
263 | {
264 | void *value;
265 | mthread_t tid;
266 | signal(SIGUSR1, handler);
267 | running = 1;
268 | MCHECK(mthread_create(&tid, NULL, infinite, NULL));
269 | MCHECK(mthread_kill(tid, SIGUSR1));
270 | MCHECK(mthread_join(tid, &value));
271 | if((int)value == 128) {
272 | fprintf(stdout, "TEST PASSED\n\n");
273 | }
274 | else {
275 | fprintf(stdout, "TEST FAILED\n\n");
276 | exit(EXIT_FAILURE);
277 | }
278 | }
279 |
280 | printf("-------------------------------------------\n");
281 | printf("Thread Exit\n");
282 | printf("-------------------------------------------\n");
283 | printf("1] Created Thread Uses Return To Exit\n");
284 | {
285 | void *value;
286 | mthread_t tid;
287 |
288 | MCHECK(mthread_create(&tid, NULL, thread1, NULL));
289 | MCHECK(mthread_join(tid, &value));
290 | fprintf(stdout, "Expected Exit Status is %d\n", 64);
291 | fprintf(stdout, "Actual Exit Status is %d\n", (int) value);
292 | if((int)value == 64) {
293 | fprintf(stdout, "TEST PASSED\n\n");
294 | }
295 | else {
296 | fprintf(stdout, "TEST FAILED\n\n");
297 | exit(EXIT_FAILURE);
298 | }
299 |
300 | }
301 | printf("2] Created Thread Uses mthread_exit()\n");
302 | {
303 | void *value;
304 | mthread_t tid;
305 |
306 | MCHECK(mthread_create(&tid, NULL, thread2, NULL));
307 | MCHECK(mthread_join(tid, &value));
308 | fprintf(stdout, "Expected Exit Status is %d\n", 2);
309 | fprintf(stdout, "Actual Exit Status is %d\n", (int) value);
310 | if((int)value == 2) {
311 | fprintf(stdout, "TEST PASSED\n\n");
312 | }
313 | else {
314 | fprintf(stdout, "TEST FAILED\n\n");
315 | exit(EXIT_FAILURE);
316 | }
317 | }
318 |
319 | printf("-------------------------------------------\n");
320 | printf("Miscellaneous\n");
321 | printf("-------------------------------------------\n");
322 |
323 | printf("1] Create thread inside another thread\n");
324 | {
325 | count = 0;
326 | mthread_t tid;
327 | MCHECK(mthread_create(&tid, NULL, threadtwo, NULL));
328 | MCHECK(mthread_join(tid, NULL));
329 | if (count == 2) {
330 | printf("TEST PASSED\n\n");
331 | }
332 | else {
333 | printf("TEST FAILED\n\n");
334 | exit(EXIT_FAILURE);
335 | }
336 | }
337 | printf("2] Scheduling between three threads\n");
338 | {
339 | mthread_t tid[3];
340 | for(int i = 0; i < 3; i++) {
341 | MCHECK(mthread_create(&tid[i], NULL, keep_going, NULL));
342 | }
343 | for(int i = 0; i < 3; i++) {
344 | MCHECK(mthread_join(tid[i], NULL));
345 | }
346 | printf("TEST PASSED\n\n");
347 | }
348 |
349 | return 0;
350 | }
--------------------------------------------------------------------------------
/many-one/test/spin_test.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Example code for using spinlocks. This program creates 5 threads
3 | * each of which tries to increment two variables - one shared and one
4 | * individual. To access the shared variable spinlocks are used to guarantee
5 | * mutual exclusion and race conditions. Absence of race conditions are checked
6 | * by checking if the sum of inidividual values is same as that of the shared
7 | * variable.
8 | */
9 |
10 | #define _GNU_SOURCE
11 | #include "mthread.h"
12 | #include
13 | #include
14 | #include
15 | #include
16 |
17 | #define MCHECK(FCALL) \
18 | { \
19 | int result; \
20 | if ((result = (FCALL)) != 0) { \
21 | fprintf(stderr, "FATAL: %s (%s)", strerror(result), #FCALL); \
22 | exit(-1); \
23 | } \
24 | }
25 |
26 |
27 | #define print(str) write(1, str, strlen(str))
28 |
29 | long long c = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, running = 1;
30 |
31 | mthread_spinlock_t lock;
32 |
33 | void *thread1(void *arg) {
34 | while(running == 1) {
35 | mthread_spin_lock(&lock);
36 | c++;
37 | mthread_spin_unlock(&lock);
38 | c1++;
39 | }
40 | }
41 |
42 | void *thread2(void *arg) {
43 | while(running == 1) {
44 | mthread_spin_lock(&lock);
45 | c++;
46 | mthread_spin_unlock(&lock);
47 | c2++;
48 | }
49 | }
50 |
51 | void *thread3(void *arg) {
52 | while(running == 1) {
53 | mthread_spin_lock(&lock);
54 | c++;
55 | mthread_spin_unlock(&lock);
56 | c3++;
57 | }
58 | }
59 |
60 | void *thread4(void *arg) {
61 | while(running == 1) {
62 | mthread_spin_lock(&lock);
63 | c++;
64 | mthread_spin_unlock(&lock);
65 | c4++;
66 | }
67 | }
68 |
69 | void *thread5(void *arg) {
70 | while(running == 1) {
71 | mthread_spin_lock(&lock);
72 | c++;
73 | mthread_spin_unlock(&lock);
74 | c5++;
75 | }
76 | }
77 |
78 | int main(int argc, char **argv) {
79 | mthread_t th1, th2, th3, th4, th5;
80 |
81 | fprintf(stdout, "----------------------------------\n");
82 | fprintf(stdout, "Thread Spinlocks\n");
83 |
84 | mthread_init();
85 | mthread_spin_init(&lock);
86 |
87 | MCHECK(mthread_create(&th1, NULL, thread1, NULL));
88 | MCHECK(mthread_create(&th2, NULL, thread2, NULL));
89 | MCHECK(mthread_create(&th3, NULL, thread3, NULL));
90 | MCHECK(mthread_create(&th4, NULL, thread4, NULL));
91 | MCHECK(mthread_create(&th5, NULL, thread5, NULL));
92 | fprintf(stdout, "Created 5 threads\n");
93 | fprintf(stdout, "Letting threads run\n");
94 |
95 | for(long long int i = 0; i < 1000000000; i++);
96 |
97 | running = 0;
98 |
99 | MCHECK(mthread_join(th1, NULL));
100 | MCHECK(mthread_join(th2, NULL));
101 | MCHECK(mthread_join(th3, NULL));
102 | MCHECK(mthread_join(th4, NULL));
103 | MCHECK(mthread_join(th5, NULL));
104 | fprintf(stdout, "Joined on all 5 threads\n");
105 |
106 | fprintf(stdout, "Thread 1 = %lld\n", c1);
107 | fprintf(stdout, "Thread 2 = %lld\n", c2);
108 | fprintf(stdout, "Thread 3 = %lld\n", c3);
109 | fprintf(stdout, "Thread 4 = %lld\n", c4);
110 | fprintf(stdout, "Thread 5 = %lld\n", c5);
111 | fprintf(stdout, "t1 + t2 + t3 + t4 + t5 = %lld\n", c1+c2+c3+c4+c5);
112 | fprintf(stdout, "Shared Variable = %lld\n", c);
113 | if(c1+c2+c3+c4+c5 == c) {
114 | fprintf(stdout, "TEST PASSED\n");
115 | }
116 | else{
117 | fprintf(stdout, "Test failed\n");
118 | }
119 | fflush(stdout);
120 | fprintf(stdout, "----------------------------------\n");
121 |
122 | return 0;
123 | }
--------------------------------------------------------------------------------
/many-one/valgrind.sh:
--------------------------------------------------------------------------------
1 | #!/bin/zsh
2 |
3 | if [ $# -eq 0 ]; then
4 | echo "Usage ./valgrind.sh "
5 | else
6 | valgrind --leak-check=full \
7 | --track-origins=yes \
8 | --show-leak-kinds=all \
9 | --verbose \
10 | --log-file=valgrind-out.txt \
11 | ./bin/$1 "${@:2}"
12 | fi
13 |
14 | # --leak-check=full : each individual leak will be shown in detail
15 | # --track-origins=yes : tracks the origins of uninitialized values,
16 | # which could be very useful for memory errors
17 | # --show-leak-kinds=all: show all of "definite, indirect, possible,
18 | # reachable" leak kinds in the "full" report
19 | # --verbose : tells you about unusual behavior of your program
20 | # --log-file : write to a file
--------------------------------------------------------------------------------
/one-one/Makefile:
--------------------------------------------------------------------------------
1 | SRC_DIR := src
2 | OBJ_DIR := obj
3 | TEST_DIR := test
4 | BIN_DIR := bin
5 | DOC_DIR := docs
6 |
7 | SRC := $(wildcard $(SRC_DIR)/*.c)
8 | # $(info SRC is $(SRC))
9 |
10 | OBJ := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)
11 | # $(info OBJ is $(OBJ))
12 |
13 | TEST_SRC := $(wildcard $(TEST_DIR)/*.c)
14 | # $(info TEST_SRC is $(TEST_SRC))
15 |
16 | TEST_OBJ := $(TEST_SRC:$(TEST_DIR)/%.c=$(TEST_DIR)/%.o)
17 | # $(info TEST_OBJ is $(TEST_OBJ))
18 |
19 | EXE := $(addprefix $(BIN_DIR)/, $(notdir $(basename $(TEST_SRC))))
20 | # $(info EXE is $(EXE))
21 |
22 | CPPFLAGS := -I include
23 | CFLAGS := -g -Wall -fpic
24 | # -g : For debugging purposes
25 | # -Wall : Print all warnings
26 | # -fpic : Use Position Independent Code. It means that the generated machine code is not dependent on being located at a specific address in order to work Ex. Jumps would be generated as relative rather than absolute
27 | TESTCFLAGS := -Wno-int-to-pointer-cast -Wno-pointer-to-int-cast -Wno-return-type
28 | LIB := libmthread.a
29 | LIBSO := libmthread.so
30 | LDFLAGS := -L.
31 | # LDLIBS := -lm
32 |
33 | CC := gcc
34 | AR := /usr/bin/ar
35 | RANLIB := /usr/bin/ranlib
36 | .PHONY: all clean lib exe docs
37 |
38 | DEBUG := 1
39 | ifeq ($(DEBUG),1)
40 | CFLAGS += -DDEBUG
41 | endif
42 |
43 | all: $(LIBSO) $(LIB) $(EXE) $(LIBSO)
44 |
45 | $(LIBSO) : $(OBJ)
46 | $(CC) -shared $(OBJ) -o $@
47 |
48 | $(LIB) : $(OBJ)
49 | $(AR) rcs $(LIB) $(OBJ)
50 | $(RANLIB) $(LIB)
51 |
52 | $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c | $(OBJ_DIR)
53 | $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
54 |
55 | $(BIN_DIR)/%: $(TEST_DIR)/%.o $(LIB)
56 | $(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@
57 |
58 | $(TEST_DIR)/%.o: $(TEST_DIR)/%.c | $(OBJ_DIR)
59 | $(CC) $(CPPFLAGS) $(CFLAGS) $(TESTCFLAGS) -c $< -o $@
60 |
61 | $(OBJ_DIR):
62 | mkdir $@
63 |
64 | docs:
65 | doxygen $(DOC_DIR)/doxy-config
66 |
67 | clean:
68 | $(RM) -rf $(OBJ) $(TEST_OBJ) $(LIB) $(EXE) $(LIBSO) $(DOC_DIR)/html $(DOC_DIR)/latex
--------------------------------------------------------------------------------
/one-one/README.md:
--------------------------------------------------------------------------------
1 | # One-One Threading Model
2 |
3 | 
4 |
5 | ## Thread Library Initialisation
6 |
7 | + `mthread_init()` initializes the mthread library. It has to be the first mthread API function call in an application, and is mandatory. It's usually done at the begin of the `main()` function of the application. This implicitly initialises the data structures and transforms the single execution unit of the current process into a thread (the 'main' thread). It returns 0 on success.
8 |
9 | ## Thread Creation
10 |
11 | + On Linux, threads and processes are treated the same. They are both considered to be tasks. One process may consists of many threads.
12 |
13 | + Every thread has it's own TID (Thread ID), saved registers, stack pointer, instruction pointer, stack(local variables, return addresses, etc.), signal mask, and priority (scheduling information) and shares everything else with the parent process depending on flags used while cloning.
14 | + Scheduling is managed by the kernel scheduler itself. So no priority is maintained.
15 | + We need to maintain a separate stack and it's size per thread.
16 |
17 | + On Linux, kernel threads are created with the `clone` system call. It is similar to fork (creates a task which is executing the current program), however it differs in that clone specifies which resources should be shared. To create a thread, we call clone to create a task which shares as much as possible: The memory space, file descriptors and signal handlers, etc.
18 |
19 | + We allocate the memory that is to be used for the thread's stack using `mmap(2)` rather than `malloc(3)` because `mmap(2)` allocates a block of memory that starts on a page boundary and is a multiple of the page size. This is useful since we want to establish a guard page (a page with protection PROT_NONE) at the end of the stack using `mprotect(2)`.
20 |
21 | + The stack pointer passed to clone must reference the top of the stack, since on most processors the stack grows down. This is done by adding the size of the region to the base of the mmap'ed region. To avoid a memory leak, the stack must be freed once the thread has exited.
22 |
23 | + For book-keeping, thread specific data is maintained in a Thread Control Block (TCB). On creation of the every thread using `mthread_create()`, a TCB is allocated and initialized accordingly.
24 |
25 | + The new thread terminates in one of the following ways:
26 | + It calls `mthread_exit()`, specifying an exit status value that is available to another thread in the same process that calls `mthread_join()`.
27 | + It returns from `start_routine()`. This is equivalent to calling mthread_exit() with the value supplied in the return statement.
28 | + Any of the threads in the process calls `exit(3)`, or the main thread performs a return from main(). This causes the termination of all threads in the process.
29 |
30 | + To replicate above behaviour, the user's `start_function(args)` are wrapped in an internal `mthread_start()` function.
31 |
32 | + To change attributes of a thread like the stack size, stack base, name for user level debugging and it's detach state, an attribute object of threads is passed as the second argument to `mthread_create()`. The user allocates it, and then calls `mthread_attr_init` to intialize it and `mthread_attr_destroy` to clean it up. For more info, refer thread attribute handling.
33 |
34 | + On succesful thread creation, the thread library provides a **thread handle** as a return value which can be further used in different thread control functions.
35 |
36 | ## Thread Attribute Handling
37 |
38 | Attribute objects are used in mthread to store attributes for to be spawned threads. They are stand-alone/unbound attribute objects i.e. they cannot modify attributes of existing threads. The following attribute fields exists in attribute objects:
39 |
40 | + MTHREAD_ATTR_NAME (read-write) \[char *\]
41 | Name of thread (up to 64 characters are stored only), mainly for debugging purposes.
42 |
43 | + MTHREAD_ATTR_JOINABLE (read-write) \[int\]
44 | The thread detachment type, JOINABLE indicates a joinable thread, DETACHED indicates a detached thread.
45 |
46 | + MTHREAD_ATTR_STACK_SIZE (read-write) \[unsigned int\]
47 | The thread stack size in bytes. Use lower values with great care!
48 |
49 | + MTHREAD_ATTR_STACK_ADDR (read-write) \[char *\]
50 | A pointer to the lower address of a chunk of malloc(3)'ed memory for the stack.
51 |
52 | `mthread_attr_t mthread_attr_new(void);`
53 | This returns a new unbound attribute object. An implicit mthread_attr_init() is done on it. Any queries on this object just fetch stored attributes from it. And attribute modifications just change the stored attributes. Use such attribute objects to pre-configure attributes for to be spawned threads.
54 |
55 | `int mthread_attr_init(mthread_attr_t attr);`
56 | This initializes an attribute object attr to the default values:
57 | MTHREAD_ATTR_NAME := 'Unknown',
58 | MTHREAD_ATTR_JOINABLE := JOINABLE,
59 | MTHREAD_ATTR_STACK_SIZE := DEFAULT,
60 | MTHREAD_ATTR_STACK_ADDR := NULL.
61 |
62 | `int mthread_attr_set(mthread_attr_t attr, int field, ...);`
63 | This sets the attribute field in attr to a value specified as an additional argument on the variable argument list. The following attribute fields and argument pairs can be used:
64 |
65 | | Attribute | Type |
66 | |---------------------------|---------------|
67 | | MTHREAD_ATTR_NAME | char * |
68 | | MTHREAD_ATTR_JOINABLE | int |
69 | | MTHREAD_ATTR_STACK_SIZE | unsigned int |
70 | | MTHREAD_ATTR_STACK_ADDR | void * |
71 |
72 | `int mthread_attr_get(mthread_attr_t attr, int field, ...);`
73 | This retrieves the attribute field in attr and stores its value in the variable specified through a pointer in an additional argument on the variable argument list. The following fields and argument pairs can be used:
74 |
75 | | Attribute | Type |
76 | |---------------------------|---------------|
77 | | MTHREAD_ATTR_NAME | char ** |
78 | | MTHREAD_ATTR_JOINABLE | int * |
79 | | MTHREAD_ATTR_STACK_SIZE | unsigned int *|
80 | | MTHREAD_ATTR_STACK_ADDR | void ** |
81 |
82 | `int mthread_attr_destroy(mthread_attr_t attr);`
83 | This destroys a attribute object attr. After this attr is no longer a valid attribute object.
84 |
85 | ## Thread Joining
86 |
87 | + The `mthread_join()` function waits for the thread specified by thread to terminate. If that thread has already terminated, then `mthread_join()` returns immediately. The thread specified by thread must be joinable.
88 |
89 | + A thread may have to wait for the completion of another thread. If the caller thread waits for an incomplete target thread to join, then it will halt till the target thread exits. This wait is implemented using `futex(2)`.
90 |
91 | + When the thread was created, a variable of the TCB was set to it's TID. By passing CLONE_CHILD_CLEARTID to `clone(2)`, it is made sure that this variable has the TID as long as the thread is running. It also clears (zero) the TID at the location pointed by the variable when the child exits, and does a wakeup on the futex at that address.
92 |
93 | + Even if a thread has finished execution, none of its allocated resources are freed. The resources of the thread are released only after the program exits to improve time complexity.
94 |
95 | + A thread must be joined on only once. Any further joins on an already joined thread will return errors.
96 |
97 | + All of the threads in a process are peers: any thread can join with any other thread in the process.
98 |
99 | ## Thread Signals
100 |
101 | + Signals may be sent to a specific thread or a thread group using `mthread_kill()`.
102 |
103 | + For this `tgkill(2)` was used to direct the signals to the target thread.
104 |
105 | + Note : Signal dispositions and actions are process-wide: if an unhandled signal is delivered to a thread, then it will affect (terminate, stop, continue, be ignored in) all members of the thread group.
106 |
107 | ## Thread Exiting
108 |
109 | + As mentioned previously, a thread can exit using the `mthread_exit()` function. The thread can also return a value while it is exiting, to be returned to the thread joining on it. This is done by storing it's result in the TCB.
110 |
111 | + When the thread was created, `clone(2)` was passed the `mthread_start()` as start function of the thread. To exit safely, it is important that `mthread_exit()` returns to `mthread_start()` since that is how clone will return. For this `sigsetjmp(3)` and `siglongjmp(3)` are used.
112 |
113 | ## Thread Yielding
114 |
115 | + Yield execution control to next thread by simply calling `mthread_yield()`. It is simply a wrapper for a `sched_yield(2)`
116 |
117 | ## Thread Detachment
118 |
119 | + The `mthread_detach()` function marks the thread passed as argument as detached. Any other thread trying to join on a detached thread will result in an error.
120 |
121 | ## Thread Equality
122 |
123 | + The `mthread_equal()` function checks whether the threads identified by their thread handles are the same or not. Returns 0 if equal and non-zero if not.
124 |
125 | ## Synchronisation Primitives
126 |
127 | ### Spinlocks
128 |
129 | A spinlock is a lock which causes a thread trying to acquire it to simply wait in a loop ("spin") while repeatedly checking if the lock is available. The advantage of a spinlock is that the thread is kept active and does not enter a sleep-wait for a mutex to become available, thus can perform better in certain cases than typical blocking-sleep-wait style mutexes.
130 |
131 | Functions used in conjunction with the spinlock:
132 |
133 | Creating/Destroying:
134 | `mthread_spinlock_init()`
135 | `mthread_spinlock_destroy()`
136 |
137 | Attempt to lock the spinlock (returns immediately with EBUSY if locked):
138 | `mthread_spinlock_trylock()`
139 |
140 | Lock the spinlock (blocks until spinlock is unlocked):
141 | `mthread_spinlock_lock()`
142 |
143 | Unlock the spinlock:
144 | `mthread_spinlock_unlock()`
145 |
146 | ### Mutexes
147 |
148 | Mutexes are used to prevent data inconsistencies due to race conditions (when two or more threads need to perform operations on the same memory area, but the results of computations depends on the order in which these operations are performed). Mutexes are used for serializing shared resources. Anytime a global resource is accessed by more than one thread the resource should have a mutex associated with it. One can apply a mutex to protect a segment of memory ("critical region") from other threads.
149 |
150 | Functions used in conjunction with the mutex:
151 |
152 | Creating/Destroying:
153 | `mthread_mutex_t mutex = MTHREAD_MUTEX_INITIALIZER;`
154 | `mthread_mutex_init()`
155 | `mthread_mutex_destroy()`
156 |
157 | Attempt to lock the mutex (returns immediately with EBUSY if locked):
158 | `mthread_mutex_trylock()`
159 |
160 | Lock the mutex (blocks until mutex is unlocked):
161 | `mthread_mutex_lock()`
162 |
163 | Unlock the mutex:
164 | `mthread_mutex_unlock()`
165 |
166 | ### Condition Variable
167 |
168 | While mutexes implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data. The condition variable mechanism allows threads to suspend execution and relinquish the processor until some condition is true. A condition variable must always be associated with a mutex to avoid a race condition created by one thread preparing to wait and another thread which may signal the condition before the first thread actually waits on it resulting in a deadlock. The thread will be perpetually waiting for a signal that is never sent. Any mutex can be used, there is no explicit link between the mutex and the condition variable.
169 |
170 | Functions used in conjunction with the condition variable:
171 |
172 | Creating/Destroying:
173 | `mthread_cond_t cond = MTHREAD_COND_INITIALIZER;`
174 | `mthread_cond_init()`
175 | `mthread_cond_destroy()`
176 |
177 | Waiting on condition:
178 | `mthread_cond_wait()`
179 |
180 | Waking thread based on condition:
181 | `mthread_cond_signal()`
182 |
183 | ### Semaphores
184 |
185 | A Semaphore is a thread synchronization construct that can be used either to send signals between threads to avoid missed signals, or to guard a critical section like you would with a lock. Semaphores are also specifically designed to support an efficient waiting mechanism. If a thread can’t proceed until some change occurs, it is undesirable for that thread to be looping and repeatedly checking the state until it changes. In this case semaphore can be used to represent the right of a thread to proceed. A non-zero value means the thread
186 | should continue, zero means to hold off. When a thread attempts to decrement a unavailable semaphore (with a zero value), it efficiently waits until another thread increments the semaphore to signal the state change that will allow it to proceed.
187 |
188 | Functions used in conjunction with the semaphore:
189 |
190 | Creating/Destroying:
191 | `mthread_sem_t sem = MTHREAD_SEM_INITIALIZER;`
192 | `mthread_sem_init()`
193 | `mthread_sem_destroy()`
194 |
195 | Waiting on condition:
196 | `mthread_sem_wait()`
197 |
198 | Waking thread based on condition:
199 | `mthread_sem_post()`
200 |
--------------------------------------------------------------------------------
/one-one/docs/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayank-02/multithreading-library/3df2df3068c80851103e1d910e0d21b5ac8918ff/one-one/docs/logo.png
--------------------------------------------------------------------------------
/one-one/docs/one-to-one.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mayank-02/multithreading-library/3df2df3068c80851103e1d910e0d21b5ac8918ff/one-one/docs/one-to-one.png
--------------------------------------------------------------------------------
/one-one/include/mthread.h:
--------------------------------------------------------------------------------
1 | #ifndef _MTHREAD_H_
2 | #define _MTHREAD_H_
3 |
4 | #include "types.h"
5 |
6 | #define MTHREAD_ATTR_DEFAULT NULL
7 |
8 | enum {
9 | DETACHED,
10 | JOINABLE,
11 | JOINED
12 | };
13 |
14 | enum {
15 | MTHREAD_ATTR_GET,
16 | MTHREAD_ATTR_SET
17 | };
18 |
19 | enum {
20 | MTHREAD_ATTR_NAME, /* RW [char *] name of thread */
21 | MTHREAD_ATTR_JOINABLE, /* RW [int] detachment type */
22 | MTHREAD_ATTR_STACK_SIZE, /* RW [size_t] stack */
23 | MTHREAD_ATTR_STACK_ADDR /* RW [void *] stack lower */
24 | };
25 |
26 | /* Thread attribute functions */
27 | struct mthread_attr;
28 | typedef struct mthread_attr mthread_attr_t;
29 |
30 | mthread_attr_t *mthread_attr_new(void);
31 |
32 | int mthread_attr_init(mthread_attr_t *attr);
33 |
34 | int mthread_attr_set(mthread_attr_t *attr, int field, ...);
35 |
36 | int mthread_attr_get(mthread_attr_t *attr, int field, ...);
37 |
38 | int mthread_attr_destroy(mthread_attr_t *attr);
39 |
40 | /* Thread control functions */
41 |
42 | /**
43 | * Initialise the threading library
44 | */
45 | int mthread_init(void);
46 |
47 | /**
48 | * Create a new thread starting at the routine given, which will
49 | * be passed arg.
50 | */
51 | int mthread_create(mthread_t *thread, mthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
52 |
53 | /**
54 | * Wait until the specified thread has exited.
55 | * Returns the value returned by that thread's
56 | * start function.
57 | */
58 | int mthread_join(mthread_t thread, void **retval);
59 |
60 | /**
61 | * Yield to scheduler
62 | */
63 | void mthread_yield(void);
64 |
65 | /**
66 | * Exit the calling thread with return value retval.
67 | */
68 | void mthread_exit(void *retval);
69 |
70 | /**
71 | * Send signal specified by sig to thread
72 | */
73 | int mthread_kill(mthread_t thread, int sig);
74 |
75 | /**
76 | * Mark the thread as detached
77 | */
78 | int mthread_detach(mthread_t thread);
79 |
80 | /**
81 | * Compare Thread IDs
82 | */
83 | int mthread_equal(mthread_t t1, mthread_t t2);
84 |
85 |
86 | /* Synchronisation primitives */
87 | struct mthread_spinlock;
88 | typedef struct mthread_spinlock mthread_spinlock_t;
89 |
90 | /*
91 | * Initialise the spinlock
92 | */
93 | int mthread_spin_init(mthread_spinlock_t *lock);
94 |
95 | /*
96 | * Lock the spinlock
97 | */
98 | int mthread_spin_lock(mthread_spinlock_t *lock);
99 |
100 | /*
101 | * Try locking the spinlock
102 | */
103 | int mthread_spin_trylock(mthread_spinlock_t *lock);
104 |
105 | /*
106 | * Unlock the spinlock
107 | */
108 | int mthread_spin_unlock(mthread_spinlock_t *lock);
109 |
110 | #define MTHREAD_MUTEX_INITIALIZER { 0 }
111 | struct mthread_mutex;
112 | typedef struct mthread_mutex mthread_mutex_t;
113 |
114 | /*
115 | * Initialise the mutex
116 | */
117 | int mthread_mutex_init(mthread_mutex_t *mutex);
118 |
119 | /*
120 | * Try locking the mutex
121 | */
122 | int mthread_mutex_trylock(mthread_mutex_t *mutex);
123 |
124 | /*
125 | * Lock the mutex
126 | */
127 | int mthread_mutex_lock(mthread_mutex_t *mutex);
128 |
129 | /*
130 | * Unlock the mutex
131 | */
132 | int mthread_mutex_unlock(mthread_mutex_t *mutex);
133 |
134 | #define MTHREAD_COND_INITIALIZER { 0 , 0 }
135 | struct mthread_cond;
136 | typedef struct mthread_cond mthread_cond_t;
137 |
138 | int mthread_cond_init(mthread_cond_t *cond);
139 |
140 | int mthread_cond_wait(mthread_cond_t *cond, mthread_mutex_t *mutex);
141 |
142 | int mthread_cond_signal(mthread_cond_t *cond);
143 |
144 | #define MTHREAD_SEM_INITIALIZER { 0 }
145 | struct mthread_sem;
146 | typedef struct mthread_sem mthread_sem_t;
147 |
148 | int mthread_sem_init(mthread_sem_t *sem, uint32_t initval);
149 |
150 | int mthread_sem_wait(mthread_sem_t *sem);
151 |
152 | int mthread_sem_post(mthread_sem_t *sem);
153 |
154 | #endif
--------------------------------------------------------------------------------
/one-one/include/queue.h:
--------------------------------------------------------------------------------
1 | #include "mthread.h"
2 |
3 | /// Node of a queue
4 | typedef struct node {
5 | /// TCB
6 | mthread *thd;
7 | /// Pointer to next node
8 | struct node *next;
9 | } node;
10 |
11 | /// Queue
12 | typedef struct queue {
13 | /// Count of nodes in the queue
14 | int count;
15 | /// Pointer to head node
16 | node *head;
17 | /// Pointer to tail node
18 | node *tail;
19 | } queue;
20 |
21 | void initialize(queue *q);
22 |
23 | int isempty(queue *q);
24 |
25 | void enqueue(queue *q, mthread *thd);
26 |
27 | mthread *dequeue(queue *q);
28 |
29 | int getcount(queue *q);
30 |
31 | void display(queue *q);
32 |
33 | mthread *search_on_tid(queue *q, mthread_t tid);
34 |
35 | int destroy(queue *q);
--------------------------------------------------------------------------------
/one-one/include/stack.h:
--------------------------------------------------------------------------------
1 | #ifndef _STACK_H_
2 | #define _STACK_H_
3 |
4 | size_t get_page_size(void);
5 |
6 | size_t get_stack_size(void);
7 |
8 | void * allocate_stack(size_t stack_size);
9 |
10 | int deallocate_stack(void *base, size_t stack_size);
11 |
12 | #endif
--------------------------------------------------------------------------------
/one-one/include/types.h:
--------------------------------------------------------------------------------
1 | #ifndef _TYPES_H_
2 | #define _TYPES_H_
3 |
4 | #include
5 | #include
6 | #include
7 |
8 | /// Maximium length of name of thread
9 | #define MTHREAD_TCB_NAMELEN 64
10 |
11 | /// Thread Handle
12 | typedef pid_t mthread_t;
13 |
14 | /// Thread Control Block
15 | typedef struct mthread {
16 | /// Thread ID
17 | mthread_t tid;
18 |
19 | /// Futex
20 | int32_t futex;
21 |
22 | /// Start position of the code to be executed
23 | void *(*start_routine) (void *);
24 |
25 | /// The argument passed to the function
26 | void *arg;
27 |
28 | /// The result of the thread function
29 | void *result;
30 |
31 | /// Padding for stack canary
32 | int64_t padding;
33 |
34 | /// Base pointer to stack
35 | void *stack_base;
36 |
37 | /// Size of stack
38 | size_t stack_size;
39 |
40 | /// Detachment type
41 | int detach_state;
42 |
43 | /// Name of process for debugging
44 | char name[MTHREAD_TCB_NAMELEN];
45 |
46 | /// For exiting safely
47 | sigjmp_buf context;
48 | } mthread;
49 |
50 | /// Thread Attribute Structure
51 | struct mthread_attr {
52 | /// Name for debugging
53 | char a_name[MTHREAD_TCB_NAMELEN];
54 |
55 | /// Detachment type
56 | int a_detach_state;
57 |
58 | /// Base pointer to stack
59 | void *a_stack_base;
60 |
61 | /// Size of stack
62 | size_t a_stack_size;
63 | };
64 |
65 | /// States of a lock
66 | #define CONTESTED (2u)
67 | #define LOCKED (1u)
68 | #define UNLOCKED (0u)
69 |
70 | /// Spinlock structure
71 | struct mthread_spinlock {
72 | /// Value of spinlock
73 | int value;
74 | };
75 |
76 | /// Mutex structure
77 | struct mthread_mutex {
78 | /// Value of mutex
79 | int value;
80 | };
81 |
82 | /// Condition Variable structure
83 | struct mthread_cond {
84 | /// Current value of condition variable
85 | int value;
86 |
87 | /// Previous value of condition variable
88 | unsigned int previous;
89 | };
90 |
91 | /// Semaphore structure
92 | struct mthread_sem {
93 | /// Value of semaphore
94 | int value;
95 | };
96 |
97 | #endif
--------------------------------------------------------------------------------
/one-one/include/utils.h:
--------------------------------------------------------------------------------
1 | #ifndef _UTILS_H_
2 | #define _UTILS_H_
3 |
4 | #include
5 |
6 | size_t get_extant_process_limit(void);
7 |
8 | char *util_strncpy(char *dst, const char *src, size_t dst_size);
9 |
10 | #endif
--------------------------------------------------------------------------------
/one-one/run_tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo -e "\033[34m************************RUNNING ROBUST TEST*************************\033[0m"
4 | echo "./bin/robust_test"
5 | ./bin/robust_test
6 | echo ""
7 | echo ""
8 | echo -e "\033[34m***********************RUNNING SPINLOCK TEST************************\033[0m"
9 | echo "./bin/spin_test"
10 | ./bin/spin_test
11 | echo "5 seconds"
12 | ./bin/spin_test 5
13 | echo ""
14 | echo ""
15 | echo -e "\033[34m***********************RUNNING MUTEX TEST************************\033[0m"
16 | echo "./bin/mutex_test"
17 | ./bin/mutex_test
18 | echo "5 seconds"
19 | ./bin/mutex_test 5
20 | echo ""
21 | echo ""
22 | echo -e "\033[34m***********************RUNNING CONDVAR TEST************************\033[0m"
23 | echo "./bin/condvar_test"
24 | ./bin/condvar_test
25 | echo ""
26 | echo ""
27 | echo -e "\033[34m***********************RUNNING SEMAPHORE TEST************************\033[0m"
28 | echo "./bin/semaphore_test"
29 | ./bin/semaphore_test
30 | echo "1 10 10"
31 | ./bin/semaphore_test 1 10 10
32 | echo ""
33 | echo ""
34 | echo -e "\033[34m**********************RUNNING PERFORMANCE TEST**********************\033[0m"
35 | echo "./bin/performance_test"
36 | ./bin/performance_test
37 | echo ""
38 | echo ""
39 | echo -e "\033[34m**********************RUNNING PHILOSOPHERS TEST**********************\033[0m"
40 | echo "./bin/philosophers"
41 | ./bin/philosophers
42 | echo "2000 steps"
43 | ./bin/philosophers 2000
44 | echo ""
45 | echo ""
--------------------------------------------------------------------------------
/one-one/src/attr.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file attr.c
3 | * @brief Attribute handling functions
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include "mthread.h"
13 | #include "utils.h"
14 |
15 | /**
16 | * @brief Controls the attributes depending on the operation
17 | * @param[in] cmd Get or Set the attribute
18 | * @param[in,out] a Attribute object
19 | * @param[in] op Attribute
20 | * @param[in] ap Variable argument list corresponding to attribute
21 | * @return On success, returns 0; on error, it returns an error number
22 | */
23 | static int mthread_attr_ctrl(int cmd, mthread_attr_t *a, int op, va_list ap) {
24 | if(a == NULL)
25 | return EINVAL;
26 | switch(op) {
27 | case MTHREAD_ATTR_NAME: {
28 | /* name */
29 | if(cmd == MTHREAD_ATTR_SET) {
30 | char *src, *dst;
31 | src = va_arg(ap, char *);
32 | dst = a->a_name;
33 | util_strncpy(dst, src, MTHREAD_TCB_NAMELEN);
34 | }
35 | else {
36 | char *src, **dst;
37 | src = a->a_name;
38 | dst = va_arg(ap, char **);
39 | *dst = src;
40 | }
41 | break;
42 | }
43 | case MTHREAD_ATTR_JOINABLE: {
44 | /* detachment type */
45 | int val, *src, *dst;
46 | if(cmd == MTHREAD_ATTR_SET) {
47 | src = &val;
48 | val = va_arg(ap, int);
49 | dst = &a->a_detach_state;
50 | }
51 | else {
52 | src = &a->a_detach_state;
53 | dst = va_arg(ap, int *);
54 | }
55 | *dst = *src;
56 | break;
57 | }
58 | case MTHREAD_ATTR_STACK_SIZE: {
59 | /* stack size */
60 | size_t val, *src, *dst;
61 | if(cmd == MTHREAD_ATTR_SET) {
62 | src = &val;
63 | val = va_arg(ap, size_t);
64 | dst = &a->a_stack_size;
65 | }
66 | else {
67 | src = &a->a_stack_size;
68 | dst = va_arg(ap, size_t *);
69 | }
70 | *dst = *src;
71 | break;
72 | }
73 | case MTHREAD_ATTR_STACK_ADDR: {
74 | /* stack address */
75 | void *val, **src, **dst;
76 | if(cmd == MTHREAD_ATTR_SET) {
77 | src = &val;
78 | val = va_arg(ap, void *);
79 | dst = &a->a_stack_base;
80 | }
81 | else {
82 | src = &a->a_stack_base;
83 | dst = va_arg(ap, void **);
84 | }
85 | *dst = *src;
86 | break;
87 | }
88 | default:
89 | return EINVAL;
90 | }
91 | return 0;
92 | }
93 |
94 | /**
95 | * @brief Make a new thread attributes object and initialise it
96 | * @return On success, returns pointer to attribute object;
97 | * on error, it returns NULL
98 | */
99 | mthread_attr_t *mthread_attr_new(void) {
100 | mthread_attr_t *a;
101 | a = (mthread_attr_t *) calloc(1, sizeof(mthread_attr_t));
102 | if(a == NULL) {
103 | return NULL;
104 | }
105 |
106 | mthread_attr_init(a);
107 | return a;
108 | }
109 |
110 | /**
111 | * @brief Controls the attributes depending on the operation
112 | * @param[in,out] a Attribute object to be initialised
113 | * @return On success, returns 0; on error, it returns an error number
114 | */
115 | int mthread_attr_init(mthread_attr_t *a) {
116 | if(a == NULL)
117 | return EINVAL;
118 |
119 | util_strncpy(a->a_name, "Unknown", MTHREAD_TCB_NAMELEN);
120 | a->a_detach_state = JOINABLE;
121 | a->a_stack_size = 8196 * 1024;
122 | a->a_stack_base = NULL;
123 |
124 | return 0;
125 | }
126 |
127 | /**
128 | * @brief Get particular attribute from thread attribute object
129 | * @param[in] a Attribute object
130 | * @param[in] op Attribute
131 | * @param[in] ... Variable argument list corresponding to attribute
132 | * @return On success, returns 0; on error, it returns an error number
133 | */
134 | int mthread_attr_get(mthread_attr_t *a, int op, ...) {
135 | va_list ap;
136 | int ret;
137 |
138 | va_start(ap, op);
139 | ret = mthread_attr_ctrl(MTHREAD_ATTR_GET, a, op, ap);
140 | va_end(ap);
141 | return ret;
142 | }
143 |
144 | /**
145 | * @brief Set particular attribute in thread attribute object
146 | * @param[in,out] a Attribute object
147 | * @param[in] op Attribute
148 | * @param[in] ... Variable argument list corresponding to attribute
149 | * @return On success, returns 0; on error, it returns an error number
150 | */
151 | int mthread_attr_set(mthread_attr_t *a, int op, ...) {
152 | va_list ap;
153 | int ret;
154 |
155 | va_start(ap, op);
156 | ret = mthread_attr_ctrl(MTHREAD_ATTR_SET, a, op, ap);
157 | va_end(ap);
158 | return ret;
159 | }
160 |
161 | /**
162 | * @brief Destroy thread attribute
163 | * @param[in,out] a Attribute object
164 | * @return On success, returns 0; on error, it returns an error number
165 | */
166 | int mthread_attr_destroy(mthread_attr_t *a) {
167 | if(a == NULL)
168 | return EINVAL;
169 | free(a);
170 | return 0;
171 | }
--------------------------------------------------------------------------------
/one-one/src/cond.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file cond.c
3 | * @brief Condition Variable Synchronisation Primitive
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #define _GNU_SOURCE
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include "mthread.h"
16 |
17 | /**
18 | * @brief Fast user-space locking
19 | * @param[in] uaddr Pointer to futex word
20 | * @param[in] futex_op Operation to be performed
21 | * @param[in] val Expected value of the futex word
22 | * @return 0 on success; -1 on error
23 | */
24 | static inline int futex(int *uaddr, int futex_op, int val) {
25 | return syscall(SYS_futex, uaddr, futex_op, val, NULL, NULL, 0);
26 | }
27 |
28 | /**
29 | * @brief Initialise the condition variable
30 | * @param[in,out] cond Pointer to condition variable
31 | * @return Always returns 0
32 | */
33 | int mthread_cond_init(mthread_cond_t *cond) {
34 | assert(cond);
35 |
36 | atomic_init(&cond->value, 0);
37 | atomic_init(&cond->previous, 0);
38 |
39 | return 0;
40 | }
41 |
42 | /**
43 | * @brief Atomically unlocks the mutex and waits for CV to be signaled
44 | * @param[in,out] cond Pointer to condition variable
45 | * @param[in,out] mutex Pointer to associated mutex
46 | * @note The thread execution is suspended and does not consume any
47 | * CPU time until the condition variable is signaled.
48 | * @return On success, returns 0
49 | */
50 | int mthread_cond_wait(mthread_cond_t *cond, mthread_mutex_t *mutex) {
51 | assert(cond && mutex);
52 |
53 | int value = atomic_load(&cond->value);
54 | atomic_store(&cond->previous, value);
55 |
56 | mthread_mutex_unlock(mutex);
57 | futex(&cond->value, FUTEX_WAIT_PRIVATE, value);
58 | mthread_mutex_lock(mutex);
59 |
60 | return 0;
61 | }
62 |
63 | /**
64 | * @brief Restarts one of the threads that are waiting
65 | * on the condition variable
66 | * @param[in,out] cond Pointer to condition variable
67 | * @return On success, returns 0
68 | */
69 | int mthread_cond_signal(mthread_cond_t *cond) {
70 | assert(cond);
71 |
72 | unsigned value = 1u + atomic_load(&cond->previous);
73 | atomic_store(&cond->value, value);
74 |
75 | futex(&cond->value, FUTEX_WAKE_PRIVATE, 1);
76 |
77 | return 0;
78 | }
--------------------------------------------------------------------------------
/one-one/src/mthread.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file mthread.c
3 | * @brief Thread control functions
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #define _GNU_SOURCE
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 | #include
17 | #include
18 | #include
19 | #include
20 | #include "queue.h"
21 | #include "stack.h"
22 | #include "mthread.h"
23 | #include "utils.h"
24 |
25 | static size_t nproc; ///< Number of extant processes allowed
26 | static size_t stack_size; ///< Stack size
27 | static size_t page_size; ///< Page size
28 | static queue * task_q; ///< Queue containing tasks for all threads
29 | static mthread_spinlock_t lock; ///< Lock for task queue
30 |
31 | /**
32 | * @brief Fast user-space locking
33 | * @param[in] uaddr Pointer to futex word
34 | * @param[in] futex_op Operation to be performed
35 | * @param[in] val Expected value of the futex word
36 | * @return 0 on success; -1 on error
37 | */
38 | static inline int futex(int *uaddr, int futex_op, int val) {
39 | return syscall(SYS_futex, uaddr, futex_op, val, NULL, NULL, 0);
40 | }
41 |
42 | /**
43 | * @brief Get/Set architecture-specific thread state
44 | * @param[in] code Subfunction
45 | * @param[in/out] Address of value to "set" or "get"
46 | * @return On success, returns 0; on error, -1 is returned, and errno is set to indicate the error.
47 | */
48 | static inline int arch_prctl(int code, unsigned long *addr) {
49 | return syscall(SYS_arch_prctl, code, addr);
50 | }
51 |
52 | /**
53 | * @brief Sends a signal to a thread
54 | * @param[in] tgid Thread Group ID
55 | * @param[in] tid Thread ID
56 | * @param[in] sig Signal number
57 | * @return 0 on success; -1 on error
58 | */
59 | static inline int tgkill(int tgid, int tid, int sig) {
60 | return syscall(SYS_tgkill, tgid, tid, sig);
61 | }
62 |
63 | /**
64 | * @brief Cleans up all malloc(3)ed and mmap(3)ed regions
65 | */
66 | static void cleanup_handler(void) {
67 | mthread *t;
68 | int n = getcount(task_q);
69 | while(n--) {
70 | t = dequeue(task_q);
71 | if(t->detach_state == JOINED) {
72 | deallocate_stack(t->stack_base, t->stack_size);
73 | free(t);
74 | }
75 | }
76 | free(task_q);
77 | }
78 |
79 | /**
80 | * @brief Obtain information about calling thread
81 | * @return Pointer to thread handle on success, and NULL on failure
82 | */
83 | static mthread *mthread_self(void) {
84 | uint64_t ptr;
85 | pid_t tid = gettid();
86 | if(tid == getpid()){
87 | return NULL;
88 | }
89 |
90 | int err = arch_prctl(ARCH_GET_FS, &ptr);
91 | if(err == -1)
92 | return NULL;
93 |
94 | return (mthread *)ptr;
95 | }
96 |
97 | /**
98 | * @brief Wrapper around user start function
99 | * @return On success, returns 0
100 | */
101 | static int mthread_start(void *thread) {
102 | mthread *t = (mthread *)thread;
103 |
104 | if(sigsetjmp(t->context, 0) == 0)
105 | t->result = t->start_routine(t->arg);
106 |
107 | return 0;
108 | }
109 |
110 | /**
111 | * @brief Initialise the mthread library
112 | * @note It has to be the first mthread API function call in an application,
113 | * and is mandatory.
114 | * @return On success, returns 0; on error, it returns an error number
115 | */
116 | int mthread_init(void) {
117 | mthread_spin_init(&lock);
118 |
119 | task_q = calloc(1, sizeof(queue));
120 | initialize(task_q);
121 |
122 | atexit(cleanup_handler);
123 |
124 | mthread *main_thread = (mthread *) calloc(1, sizeof(mthread));
125 | main_thread->start_routine = main_thread->arg = main_thread->result = NULL;
126 | main_thread->detach_state = JOINABLE;
127 | main_thread->stack_base = NULL;
128 | main_thread->stack_size = 0;
129 | main_thread->tid = gettid();
130 | enqueue(task_q, main_thread);
131 |
132 | stack_size = get_stack_size();
133 | nproc = get_extant_process_limit();
134 | page_size = get_page_size();
135 |
136 | return 0;
137 | }
138 |
139 | /**
140 | * @brief Create a new thread
141 | * @param[in] thread Pointer to thread handle
142 | * @param[in] attr Pointer to attribute object
143 | * @param[in] start_routine Start function of the thread
144 | * @param[in] arg Arguments to be passed to the start function
145 | * @return On success, returns 0; on error, it returns an error number
146 | */
147 | int mthread_create(mthread_t *thread, mthread_attr_t *attr, void *(*start_routine)(void *), void *arg) {
148 | mthread_spin_lock(&lock);
149 |
150 | if(getcount(task_q) == nproc) {
151 | mthread_spin_unlock(&lock);
152 | return EAGAIN;
153 | }
154 |
155 | if(start_routine == NULL) {
156 | mthread_spin_unlock(&lock);
157 | return EINVAL;
158 | }
159 |
160 | mthread *t = (mthread *) calloc(1, sizeof(mthread));
161 | if(t == NULL) {
162 | mthread_spin_unlock(&lock);
163 | return EAGAIN;
164 | }
165 |
166 | t->start_routine = start_routine;
167 | t->arg = arg;
168 | t->detach_state = (attr == NULL ? JOINABLE : attr->a_detach_state);
169 | t->stack_size = (attr == NULL ? stack_size : attr->a_stack_size);
170 | t->stack_base = (attr == NULL ? NULL : attr->a_stack_base);
171 | if(t->stack_base == NULL) {
172 | t->stack_base = allocate_stack(t->stack_size);
173 | if(t->stack_base == NULL) {
174 | free(t);
175 | mthread_spin_unlock(&lock);
176 | return ENOMEM;
177 | }
178 | }
179 |
180 | if(attr == NULL)
181 | snprintf(t->name, MTHREAD_TCB_NAMELEN, "User%d", t->tid);
182 | else
183 | util_strncpy(t->name, attr->a_name, MTHREAD_TCB_NAMELEN);
184 |
185 | t->tid = clone(mthread_start,
186 | t->stack_base + t->stack_size,
187 | CLONE_VM | CLONE_FS | CLONE_FILES |
188 | CLONE_SIGHAND |CLONE_THREAD | CLONE_SYSVSEM |
189 | CLONE_SETTLS |CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID,
190 | t,
191 | &t->futex,
192 | t,
193 | &t->futex);
194 | if(t->tid == -1) {
195 | deallocate_stack(t->stack_base, t->stack_size);
196 | free(t);
197 | mthread_spin_unlock(&lock);
198 | return errno;
199 | }
200 |
201 | enqueue(task_q, t);
202 |
203 | *thread = t->tid;
204 |
205 | mthread_spin_unlock(&lock);
206 | return 0;
207 | }
208 |
209 | /**
210 | * @brief Join with a terminated thread
211 | * @param[in] thread Handle of thread to wait for
212 | * @param[in] retval To save the exit status of the target thread
213 | * @return On success, returns 0; on error, it returns an error number
214 | */
215 | int mthread_join(mthread_t thread, void **retval) {
216 | mthread_spin_lock(&lock);
217 |
218 | mthread *target = search_on_tid(task_q, thread);
219 | if(target == NULL) {
220 | mthread_spin_unlock(&lock);
221 | return ESRCH;
222 | }
223 |
224 | if(target->detach_state == DETACHED || target->detach_state == JOINED) {
225 | mthread_spin_unlock(&lock);
226 | return EINVAL;
227 | }
228 |
229 | target->detach_state = JOINED;
230 | mthread_spin_unlock(&lock);
231 |
232 | int err = futex(&target->futex, FUTEX_WAIT, target->tid);
233 | if(err == -1 && errno != EAGAIN)
234 | return err;
235 |
236 | if(retval)
237 | *retval = target->result;
238 |
239 | return 0;
240 | }
241 |
242 | /**
243 | * @brief Yield the processor
244 | */
245 | void mthread_yield(void) {
246 | sched_yield();
247 | }
248 |
249 | /**
250 | * @brief Terminate calling thread
251 | * @param[in] retval Return value of the thread
252 | * @return Does not return to the caller
253 | * @note Performing a return from the start funciton of any thread results in
254 | * an implicit call to mthread_exit()
255 | */
256 | void mthread_exit(void *retval) {
257 | mthread_spin_lock(&lock);
258 | mthread *self = mthread_self();
259 | if(self == NULL) {
260 | mthread_spin_unlock(&lock);
261 | return;
262 | }
263 |
264 | self->result = retval;
265 | mthread_spin_unlock(&lock);
266 | siglongjmp(self->context, 1);
267 | }
268 |
269 | /**
270 | * @brief Send a signal to a thread
271 | * @param[in] thread Thread handle of thread to which signal needs to be sent
272 | * @param[in] sig Signal number corresponding to signal
273 | * @return On success, returns 0; on error, it returns an error number
274 | */
275 | int mthread_kill(mthread_t thread, int sig) {
276 | if(sig == 0)
277 | return 0;
278 |
279 | pid_t tgid = getpid();
280 | int err = tgkill(tgid, thread, sig);
281 | if(err == -1)
282 | return errno;
283 |
284 | return 0;
285 | }
286 |
287 | /**
288 | * @brief Detach a thread
289 | * @param[in] thread Thread handle of thread to be detached
290 | * @return On success, returns 0; on error, it returns an error number
291 | * @note Once a thread has been detached, it can't be joined with mthread_join * or be made joinable again.
292 | */
293 | int mthread_detach(mthread_t thread) {
294 | mthread_spin_lock(&lock);
295 |
296 | mthread *target = search_on_tid(task_q, thread);
297 |
298 | if(target == NULL) {
299 | mthread_spin_unlock(&lock);
300 | return ESRCH;
301 | }
302 |
303 | if(target->detach_state == JOINED) {
304 | mthread_spin_unlock(&lock);
305 | return EINVAL;
306 | }
307 |
308 | target->detach_state = DETACHED;
309 | mthread_spin_unlock(&lock);
310 |
311 | return 0;
312 | }
313 |
314 | /**
315 | * @brief Compare Thread IDs
316 | * @param[in] t1 Thread handle of thread 1
317 | * @param[in] t2 Thread handle of thread 2
318 | * @return 0 on success, and non-zero on failure
319 | */
320 | int mthread_equal(mthread_t t1, mthread_t t2) {
321 | return t1 - t2;
322 | }
323 |
--------------------------------------------------------------------------------
/one-one/src/mutex.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file mutex.c
3 | * @brief Mutex Synchronisation Primitive
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #define _GNU_SOURCE
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 | #include "mthread.h"
17 |
18 | /**
19 | * @brief Atomic Compare and Swap
20 | * @param[in,out] lock_addr Pointer to lock
21 | * @param[in] expected Expected value of lock
22 | * @param[in] desirec Desired value of lock
23 | * @return Upon success, the macro returns true. Upon failure, the desired
24 | * value is overwritten with the value of the atomic variable and false is
25 | * returned.
26 | */
27 | static inline int atomic_cas(int *lock_addr, int expected, int desired) {
28 | return atomic_compare_exchange_strong(lock_addr, &expected, desired);
29 | }
30 |
31 | /**
32 | * @brief Fast user-space locking
33 | * @param[in] uaddr Pointer to futex word
34 | * @param[in] futex_op Operation to be performed
35 | * @param[in] val Expected value of the futex word
36 | * @return 0 on success; -1 on error
37 | */
38 | static inline int futex(int *uaddr, int futex_op, int val) {
39 | return syscall(SYS_futex, uaddr, futex_op, val, NULL, NULL, 0);
40 | }
41 |
42 | /**
43 | * @brief Atomic Compare and Exchange
44 | * Atomically performs the equivalent of:
45 | * if (*ptr == *oldval)
46 | * *ptr = newval;
47 | * @param[in,out] lock_addr Pointer to lock
48 | * @param[in] expected Expected value of lock
49 | * @param[in] desirec Desired value of lock
50 | * @return Returns the expected value
51 | */
52 | static inline int cmpxchg(int *lock_addr, int expected, int desired) {
53 | int *ep = &expected;
54 | atomic_compare_exchange_strong(lock_addr, ep, desired);
55 | return *ep;
56 | }
57 |
58 | /**
59 | * @brief Initialise the mutex
60 | * @param[in,out] mutex Pointer to mutex
61 | * @return Always returns 0
62 | */
63 | int mthread_mutex_init(mthread_mutex_t *mutex) {
64 | assert(mutex);
65 | mutex->value = UNLOCKED;
66 | return 0;
67 | }
68 |
69 | /**
70 | * @brief Lock the mutex
71 | * @param[in,out] mutex Pointer to mutex
72 | * @note If the mutex is already locked by another thread, the
73 | * calling thread is suspended until the mutex is unlocked.
74 | * @return On success, returns 0
75 | */
76 | int mthread_mutex_lock(mthread_mutex_t *mutex) {
77 | assert(mutex);
78 |
79 | int c = cmpxchg(&mutex->value, UNLOCKED, LOCKED);
80 |
81 | /*
82 | * If the lock was previously unlocked, there's nothing else for us to do.
83 | * Otherwise, we'll probably have to wait.
84 | */
85 | if(c != 0) {
86 | do {
87 |
88 | /*
89 | * If the mutex is locked, we signal that we're waiting by setting
90 | * the mutex->value to 2. A shortcut checks is it's 2 already and
91 | * avoids the atomic operation in this case.
92 | */
93 | if(c == 2 || cmpxchg(&mutex->value, LOCKED, CONTESTED) != 0) {
94 |
95 | /*
96 | * Here we have to actually sleep, because the mutex is actually
97 | * locked. Note that it's not necessary to loop around this
98 | * syscall;
99 | * A spurious wakeup will do no harm since we only exit the
100 | * do...while loop when mutex->value is indeed 0.
101 | */
102 | futex(&mutex->value, FUTEX_WAIT, CONTESTED);
103 | }
104 |
105 | /*
106 | * We're here when either:
107 | * (a) the mutex was in fact unlocked (by an intervening thread).
108 | * (b) we slept waiting for the atom and were awoken.
109 | *
110 | * So we try to lock the atom again. We set the state to 2 because
111 | * we can't be certain there's no other thread at this exact point.
112 | * So we prefer to err on the safe side.
113 | */
114 | } while((c = cmpxchg(&mutex->value, UNLOCKED, CONTESTED)) != 0);
115 | }
116 | return 0;
117 | }
118 |
119 | /**
120 | * @brief Try locking the mutex
121 | * @param[in,out] mutex Pointer to mutex
122 | * @note does not block the calling thread if the mutex is
123 | * already locked by another thread
124 | * @return On locking returns 0, else EBUSY
125 | */
126 | int mthread_mutex_trylock(mthread_mutex_t *mutex) {
127 | assert(mutex);
128 | return atomic_cas(&mutex->value, UNLOCKED, UNLOCKED) ? 0 : EBUSY;
129 | }
130 |
131 | /**
132 | * @brief Unlock the mutex
133 | * @param[in,out] mutex Pointer to mutex
134 | * @return On success, returns 0
135 | */
136 | int mthread_mutex_unlock(mthread_mutex_t *mutex) {
137 | assert(mutex);
138 | if(atomic_fetch_sub(&mutex->value, 1) != 1) {
139 | atomic_store(&mutex->value, UNLOCKED);
140 | futex(&mutex->value, FUTEX_WAKE, 1);
141 | }
142 | return 0;
143 | }
--------------------------------------------------------------------------------
/one-one/src/queue.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file queue.c
3 | * @brief Singly linked queue for thread control blocks
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include "queue.h"
12 |
13 | /**
14 | * @brief Initialise the queue
15 | * @param[in] q Pointer to queue
16 | */
17 | void initialize(queue *q) {
18 | q->count = 0;
19 | q->head = NULL;
20 | q->tail = NULL;
21 | }
22 |
23 | /**
24 | * @brief Check if queue is empty
25 | * @param[in] q Pointer to queue
26 | * @return If empty, returns 1; else 0
27 | */
28 | int isempty(queue *q) {
29 | if(q->head == NULL) {
30 | assert(q->count == 0);
31 | assert(q->tail == 0);
32 | }
33 | return (q->head == NULL);
34 | }
35 |
36 | /**
37 | * @brief Enqueue a TCB in the queue
38 | * @param[in] q Pointer to queue
39 | * @param[in] thd Pointer to TCB
40 | */
41 | void enqueue(queue *q, mthread *thd) {
42 | node *tmp = malloc(sizeof(node));
43 | tmp->thd = thd;
44 | tmp->next = NULL;
45 |
46 | if(isempty(q)) {
47 | q->head = q->tail = tmp;
48 | }
49 | else {
50 | q->tail->next = tmp;
51 | q->tail = tmp;
52 | }
53 | q->count++;
54 |
55 | return;
56 | }
57 |
58 | /**
59 | * @brief Dequeue a TCB in the queue
60 | * @param[in] q Pointer to queue
61 | * @return Pointer to TCB dequeued; Return NULL if empty
62 | */
63 | mthread *dequeue(queue *q) {
64 | if(isempty(q))
65 | return NULL;
66 |
67 | node *tmp = q->head;
68 | mthread *n = q->head->thd;
69 |
70 | q->head = q->head->next;
71 | q->count--;
72 |
73 | if(q->head == NULL) {
74 | q->tail = NULL;
75 | }
76 |
77 | free(tmp);
78 | return(n);
79 | }
80 |
81 | /**
82 | * @brief Get count of TCBs in queue
83 | * @param[in] q Pointer to queue
84 | * @return Count
85 | */
86 | int getcount(queue *q) {
87 | return q->count;
88 | }
89 |
90 | /**
91 | * @brief Display TCBs in queue
92 | * @param[in] q Pointer to queue
93 | */
94 | void display(queue *q) {
95 | if(isempty(q))
96 | return;
97 |
98 | node *runner = q->head;
99 | printf("Queue (%d): ", q->count);
100 | while(runner) {
101 | printf("%u ", runner->thd->tid);
102 | runner = runner->next;
103 | }
104 | printf("\n");
105 | }
106 |
107 | /**
108 | * @brief Search for a TCB based on TID in the queue
109 | * @param[in] q Pointer to queue
110 | * @param[in] tid TID of the target thread
111 | * @return Pointer to target thread; Return NULL if empty
112 | */
113 | mthread *search_on_tid(queue *q, mthread_t tid) {
114 | if(isempty(q))
115 | return NULL;
116 |
117 | node *runner = q->head;
118 | while(runner) {
119 | if (runner->thd->tid == tid) {
120 | return runner->thd;
121 | }
122 | runner = runner->next;
123 | }
124 | return NULL;
125 | }
126 |
127 | /**
128 | * @brief Destroy the queue
129 | * @param[in] q Pointer to queue
130 | * @return On success, returns 0; on error, -1 is returned
131 | */
132 | int destroy(queue *q) {
133 | if(!isempty(q))
134 | return -1;
135 |
136 | free(q);
137 | return 0;
138 | }
--------------------------------------------------------------------------------
/one-one/src/sem.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file sem.c
3 | * @brief Semaphore Synchronisation Primitive
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #define _GNU_SOURCE
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include "mthread.h"
16 |
17 | /**
18 | * @brief Fast user-space locking
19 | * @param[in] uaddr Pointer to futex word
20 | * @param[in] futex_op Operation to be performed
21 | * @param[in] val Expected value of the futex word
22 | * @return 0 on success; -1 on error
23 | */
24 | static inline int futex(int *uaddr, int futex_op, int val) {
25 | return syscall(SYS_futex, uaddr, futex_op, val, NULL, NULL, 0);
26 | }
27 |
28 | /**
29 | * @brief Initialise the semaphore
30 | * @param[in,out] sem Pointer to semaphore
31 | * @param[in,out] initval Value to be initialised to
32 | * @return On success, returns 0
33 | */
34 | int mthread_sem_init(mthread_sem_t *sem, uint32_t initval) {
35 | assert(sem);
36 | atomic_init(&sem->value, initval);
37 | return 0;
38 | }
39 |
40 | /**
41 | * @brief Decrements (locks) the semaphore
42 | * @param[in,out] sem Pointer to semaphore
43 | * @note If the semaphore currently has the value zero, then the
44 | * call blocks until it becomes possible to perform the decrement
45 | * @return On success, returns 0
46 | */
47 | int mthread_sem_wait(mthread_sem_t *sem) {
48 | assert(sem);
49 | uint32_t value = 1;
50 |
51 | while(!atomic_compare_exchange_weak_explicit(&sem->value,
52 | &value, value - 1,
53 | memory_order_acquire,
54 | memory_order_relaxed)) {
55 | if(value == 0) {
56 | futex(&sem->value, FUTEX_WAIT_PRIVATE, 0);
57 | value = 1;
58 | }
59 | }
60 |
61 | return 0;
62 | }
63 |
64 | /**
65 | * @brief Increments (unlocks) the semaphore
66 | * @param[in,out] sem Pointer to semaphore
67 | * @return On success, returns 0
68 | */
69 | int mthread_sem_post(mthread_sem_t *sem) {
70 | assert(sem);
71 | atomic_fetch_add_explicit(&sem->value, 1, memory_order_release);
72 | futex(&sem->value, FUTEX_WAKE_PRIVATE, 1);
73 | return 0;
74 | }
--------------------------------------------------------------------------------
/one-one/src/spin_lock.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file spin_lock.c
3 | * @brief Spinlock Synchronisation Primitive
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include "mthread.h"
12 |
13 | /**
14 | * @brief Atomic Compare and Swap
15 | * @param[in,out] lock_addr Pointer to lock
16 | * @param[in] expected Expected value of lock
17 | * @param[in] desirec Desired value of lock
18 | * @return Upon success, the macro returns true. Upon failure, the desired
19 | * value is overwritten with the value of the atomic variable and false is
20 | * returned.
21 | */
22 | static inline int atomic_cas(int *lock_addr, int expected, int desired) {
23 | return atomic_compare_exchange_strong(lock_addr, &expected, desired);
24 | }
25 |
26 | /**
27 | * @brief Initialise the spinlock
28 | * @param[out] lock Pointer to the spinlock
29 | * @note Reinitialization of a lock held by other threads may lead to
30 | * unexpected results, hence this function must be called only once
31 | * @return On success, returns 0; on error, it returns an error number
32 | */
33 | int mthread_spin_init(mthread_spinlock_t *lock) {
34 | assert(lock);
35 | lock->value = UNLOCKED;
36 | return 0;
37 | }
38 |
39 | /**
40 | * @brief Lock a spinlock
41 | * @param[in,out] lock Pointer to the spinlock
42 | * @note The call is blocking and will return only if the lock is acquired
43 | * @return On success, returns 0; on error, it returns an error number
44 | */
45 | int mthread_spin_lock(mthread_spinlock_t *lock) {
46 | assert(lock);
47 | while (!atomic_cas(&lock->value, UNLOCKED, LOCKED));
48 | return 0;
49 | }
50 |
51 | /**
52 | * @brief Try locking a spinlock
53 | * @param[in,out] lock Pointer to the spinlock
54 | * @note The call returns immediately if acquiring lock fails
55 | * @return On success, returns 0; on error, it returns an error number
56 | */
57 | int mthread_spin_trylock(mthread_spinlock_t *lock) {
58 | assert(lock);
59 | if(atomic_cas(&lock->value, UNLOCKED, LOCKED))
60 | return 0;
61 |
62 | return EBUSY;
63 | }
64 |
65 | /**
66 | * @brief Unlock a spinlock
67 | * @param[in,out] lock Pointer to the spinlock
68 | * @note Calling mthread_spin_unlock() on a lock that is not held by the
69 | * caller results in undefined behavior.
70 | * @return On success, returns 0; on error, it returns an error number
71 | */
72 | int mthread_spin_unlock(mthread_spinlock_t *lock) {
73 | assert(lock);
74 | atomic_cas(&lock->value, LOCKED, UNLOCKED);
75 | return 0;
76 | }
--------------------------------------------------------------------------------
/one-one/src/stack.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file stack.c
3 | * @brief Thread stack allocation and deallocation functions
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include "stack.h"
13 |
14 | /**
15 | * @brief Get the stack size of a thread
16 | * @return Size in bytes
17 | */
18 | size_t get_stack_size(void) {
19 | struct rlimit limit;
20 | getrlimit(RLIMIT_STACK, &limit);
21 | return limit.rlim_cur;
22 | }
23 |
24 | /**
25 | * @brief Get the page size of a thread
26 | * @return Size in bytes
27 | */
28 | size_t get_page_size(void) {
29 | return sysconf(_SC_PAGESIZE);
30 | }
31 |
32 | /**
33 | * @brief Allocate a stack
34 | * @param[in] stack_size Size of stack to mmap
35 | * @return Pointer to the base of the stack
36 | */
37 | void * allocate_stack(size_t stack_size) {
38 | size_t page_size = get_page_size();
39 |
40 | void *base = mmap(NULL,
41 | stack_size + page_size,
42 | PROT_READ | PROT_WRITE,
43 | MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK,
44 | -1,
45 | 0);
46 | if(base == MAP_FAILED)
47 | return NULL;
48 |
49 | if(mprotect(base, page_size, PROT_NONE) == -1) {
50 | munmap(base, stack_size + page_size);
51 | return NULL;
52 | }
53 |
54 | return base + page_size;
55 | }
56 |
57 | /**
58 | * @brief Deallocate a stack
59 | * @param[in] base Base of the stack
60 | * @param[in] stack_size Size of stack to mmap
61 | * @return On success, returns 0; On error, returns -1
62 | */
63 | int deallocate_stack(void *base, size_t stack_size) {
64 | size_t page_size = get_page_size();
65 | return munmap(base - page_size, stack_size + page_size);
66 | }
--------------------------------------------------------------------------------
/one-one/src/utils.c:
--------------------------------------------------------------------------------
1 | /**
2 | * @file utils.c
3 | * @brief Utility functions
4 | * @author Mayank Jain
5 | * @bug No known bugs
6 | */
7 |
8 | #include
9 | #include "utils.h"
10 |
11 | /**
12 | * @brief Get the limit of extant processes
13 | * @return Extant process limiit
14 | */
15 | size_t get_extant_process_limit(void) {
16 | struct rlimit limit;
17 | getrlimit(RLIMIT_NPROC, &limit);
18 | return limit.rlim_cur;
19 | }
20 |
21 | /**
22 | * @brief Copy a string of length atmost n bytes including '\0' character
23 | * @param[in,out] dst String to be copied into
24 | * @param[in] src String to be copied from
25 | * @param[in] dst_size Number of characters to copy
26 | * @return Pointer to first character of destination string
27 | */
28 | char *util_strncpy(char *dst, const char *src, size_t dst_size) {
29 | if(dst_size == 0)
30 | return dst;
31 |
32 | char *d = dst;
33 | char *end = dst + dst_size - 1;
34 |
35 | while(d < end) {
36 | if((*d = *src) == '\0')
37 | return dst;
38 | d++;
39 | src++;
40 | }
41 | *d = '\0';
42 |
43 | return dst;
44 | }
--------------------------------------------------------------------------------
/one-one/test/condvar_test.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Example code for using mthread condition variables. The main thread
3 | * creates three threads. Two of those threads increment a "count" variable,
4 | * while the third thread watches the value of "count". When "count"
5 | * reaches a predefined limit, the waiting thread is signaled by one of the
6 | * incrementing threads. The waiting thread "awakens" and then modifies
7 | * count. The program continues until the incrementing threads reach
8 | * TCOUNT. The main program prints the final value of count.
9 | */
10 |
11 | #include "mthread.h"
12 | #include
13 | #include
14 | #include
15 | #include
16 |
17 | #define MCHECK(FCALL) \
18 | { \
19 | int result; \
20 | if ((result = (FCALL)) != 0) { \
21 | fprintf(stderr, "FATAL: %s (%s)", strerror(result), #FCALL); \
22 | exit(-1); \
23 | } \
24 | }
25 |
26 | #define NUM_THREADS 3
27 | #define TCOUNT 10
28 | #define COUNT_LIMIT 12
29 |
30 | int count = 0;
31 | mthread_mutex_t count_mutex;
32 | mthread_cond_t count_threshold_cv;
33 |
34 | void *inc_count(void *t) {
35 | int i;
36 | long my_id = (long)t;
37 |
38 | for (i = 0; i < TCOUNT; i++) {
39 | mthread_mutex_lock(&count_mutex);
40 | count++;
41 |
42 | /*
43 | * Check the value of count and signal waiting thread when condition is
44 | * reached. Note that this occurs while mutex is locked.
45 | */
46 |
47 | if (count == COUNT_LIMIT) {
48 | printf("inc_count() : thread %ld, count = %d, threshold reached. ",
49 | my_id, count);
50 | mthread_cond_signal(&count_threshold_cv);
51 | printf("Just sent signal.\n");
52 | }
53 | printf("inc_count() : thread %ld, count = %d, unlocking mutex\n",
54 | my_id, count);
55 | mthread_mutex_unlock(&count_mutex);
56 |
57 | /* Do some work so threads can alternate on mutex lock */
58 | sleep(1);
59 | }
60 | mthread_exit(NULL);
61 | }
62 |
63 | void *watch_count(void *t) {
64 | long my_id = (long)t;
65 |
66 | printf("Starting watch_count(): thread %ld\n", my_id);
67 |
68 | /**
69 | * Lock mutex and wait for signal. Note that the mthread_cond_wait routine
70 | * will automatically and atomically unlock mutex while it waits.
71 | * Also, note that if COUNT_LIMIT is reached before this routine is run by
72 | * the waiting thread, the loop will be skipped to prevent mthread_cond_wait
73 | * from never returning.
74 | */
75 | mthread_mutex_lock(&count_mutex);
76 |
77 | while (count < COUNT_LIMIT) {
78 | printf("watch_count(): thread %ld, count = %d, Going into wait...\n", my_id, count);
79 | mthread_cond_wait(&count_threshold_cv, &count_mutex);
80 | printf("watch_count(): thread %ld, count = %d, Condition signal received\n", my_id, count);
81 | }
82 | printf("watch_count(): thread %ld, updating the value of count...\n", my_id);
83 | count += 125;
84 | printf("watch_count(): thread %ld, count now = %d\n", my_id, count);
85 | printf("watch_count(): thread %ld, unlocking mutex\n", my_id);
86 | mthread_mutex_unlock(&count_mutex);
87 | mthread_exit(NULL);
88 | }
89 |
90 | int main(int argc, char *argv[])
91 | {
92 | int i;
93 | long t1 = 1, t2 = 2, t3 = 3;
94 | mthread_t threads[3];
95 |
96 | printf("-------------------------------------------\n");
97 | printf("Thread Condition Variable\n");
98 | printf("-------------------------------------------\n");
99 |
100 | /* Initialize library, mutex and condition variable objects */
101 | mthread_init();
102 | printf("Thread Library Initialised\n");
103 |
104 | mthread_mutex_init(&count_mutex);
105 | printf("Mutex Initialised\n");
106 |
107 | mthread_cond_init(&count_threshold_cv);
108 | printf("Condition Variable Initialised\n");
109 |
110 |
111 | MCHECK(mthread_create(&threads[0], NULL, watch_count, (void *)t1));
112 | MCHECK(mthread_create(&threads[1], NULL, inc_count, (void *)t2));
113 | MCHECK(mthread_create(&threads[2], NULL, inc_count, (void *)t3));
114 |
115 | /* Wait for all threads to complete */
116 | for (i = 0; i < NUM_THREADS; i++) {
117 | MCHECK(mthread_join(threads[i], NULL));
118 | }
119 |
120 | printf("Main(): Waited and joined with %d threads.\n", NUM_THREADS);
121 | printf("Final value of count = %d.\n", count);
122 |
123 | if(count == 145) {
124 | printf("TEST PASSED\n");
125 | }
126 | else {
127 | printf("TEST FAILED\n");
128 | }
129 | printf("Exit Testcases - Thread Condition Variable\n");
130 | return 0;
131 | }
--------------------------------------------------------------------------------
/one-one/test/mutex_test.c:
--------------------------------------------------------------------------------
1 | /**
2 | * Example code for using mutexes. This program creates 5 threads
3 | * each of which tries to increment two variables - one shared and one
4 | * individual. To access the shared variable mutexes are used to guarantee
5 | * mutual exclusion and race conditions. Absence of race conditions are checked
6 | * by checking if the sum of inidividual values is same as that of the shared
7 | * variable.
8 | */
9 |
10 | #define _GNU_SOURCE
11 | #include "mthread.h"
12 | #include
13 | #include
14 | #include
15 | #include
16 |
17 | #define MCHECK(FCALL) \
18 | { \
19 | int result; \
20 | if ((result = (FCALL)) != 0) { \
21 | fprintf(stderr, "FATAL: %s (%s)", strerror(result), #FCALL); \
22 | exit(-1); \
23 | } \
24 | }
25 |
26 | #define print(str) write(1, str, strlen(str))
27 |
28 | long long c = 0, c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, running = 1;
29 |
30 | mthread_mutex_t lock;
31 |
32 | void *thread1(void *arg) {
33 | while(running == 1) {
34 | mthread_mutex_lock(&lock);
35 | c++;
36 | mthread_mutex_unlock(&lock);
37 | c1++;
38 | }
39 | }
40 |
41 | void *thread2(void *arg) {
42 | while(running == 1) {
43 | mthread_mutex_lock(&lock);
44 | c++;
45 | mthread_mutex_unlock(&lock);
46 | c2++;
47 | }
48 | }
49 |
50 | void *thread3(void *arg) {
51 | while(running == 1) {
52 | mthread_mutex_lock(&lock);
53 | c++;
54 | mthread_mutex_unlock(&lock);
55 | c3++;
56 | }
57 | }
58 |
59 | void *thread4(void *arg) {
60 | while(running == 1) {
61 | mthread_mutex_lock(&lock);
62 | c++;
63 | mthread_mutex_unlock(&lock);
64 | c4++;
65 | }
66 | }
67 |
68 | void *thread5(void *arg) {
69 | while(running == 1) {
70 | mthread_mutex_lock(&lock);
71 | c++;
72 | mthread_mutex_unlock(&lock);
73 | c5++;
74 | }
75 | }
76 |
77 | int main(int argc, char **argv) {
78 | mthread_t th1, th2, th3, th4, th5;
79 |
80 | if(argc != 2) {
81 | fprintf(stdout, "Usage: ./program