{"id":5365,"date":"2022-05-28T00:01:00","date_gmt":"2022-05-28T07:01:00","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=5365"},"modified":"2022-06-04T08:13:18","modified_gmt":"2022-06-04T15:13:18","slug":"here-a-thread-there-a-thread","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=5365","title":{"rendered":"Here a Thread, There a Thread"},"content":{"rendered":"<p>Better than forking &mdash; especially <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5358\">grandchild forking<\/a> &mdash; is to use threads. These program chunks are more manageable than forking and they don&#8217;t recreate the entire  program (process). Still, threads aren&#8217;t without their quirks. Further, they&#8217;re available only to the POSIX standard. Sorry, Windows.<br \/>\n<!--more--><br \/>\nTo deal with threads, your code must include the <code>pthread.h<\/code> header file where the <em>pthread_<\/em> family of functions are prototyped. Further, you must link in the <em>pthread<\/em> library to build the code. In Linux, add the <code>-lpthread<\/code> switch at build time. In macOS, the <em>pthread<\/em> library appears to be part of the standard C library.<\/p>\n<p>At the simplest level, your code can set a function to run as its own thread. This function runs independently from the rest of the code. It&#8217;s best that the function use only local variables, which avoids several problems I won&#8217;t get into right now. Use the <em>pthread_create()<\/em> function to launch the new thread. Here&#8217;s the visually intimidating format:<\/p>\n<p><code>int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);<\/code><\/p>\n<p>The first argument is the address of a <code>pthread_t<\/code> value. It references the thread in other <em>pthread_<\/em> family functions.<\/p>\n<p>The second argument sets various thread attributes. This value is <code>NULL<\/code> most of the time.<\/p>\n<p>The third argument is the name of the function to launch as another thread. This function&#8217;s declaration is important: It must use <em>void<\/em> arguments for flexibility. More on this topic in a few paragraphs.<\/p>\n<p>The final argument consists of any arguments passed to the function, or <code>NULL<\/code> for none.<\/p>\n<p>The function that runs the thread has this prototype:<\/p>\n<p><code>void *(*start_routine)(void *)<\/code><\/p>\n<p>This format identifies the function that&#8217;s launched into its own thread, running independently of the rest of the code.<\/p>\n<p>To demonstrate a simple thread, the following code prompts for your name &mdash; easy peasy. But before doing so, it launches the <em>thread_funct()<\/em> function as a separate thread. This function outputs asterisks every second, annoying you as you type.<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_05_28-Lesson.c\" rel=\"noopener\" target=\"_blank\">2022_05_28-Lesson.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n#include &lt;unistd.h&gt;\r\n#include &lt;pthread.h&gt;\r\n\r\nvoid *thread_funct(void *a)\r\n{\r\n    const int loop=8;\r\n    int x;\r\n\r\n    for( x=0; x&lt;loop; x++ )\r\n    {\r\n        printf(\"*\\n\");\r\n        sleep(1);\r\n    }\r\n\r\n    return(NULL);\r\n}\r\n\r\nint main()\r\n{\r\n    char buffer[BUFSIZ];\r\n    int r;\r\n    pthread_t thd;\r\n\r\n    <span class=\"comments\">\/* spawn the new thread *\/<\/span>\r\n    r = pthread_create( &amp;thd, NULL, thread_funct, NULL);\r\n    if( r!=0 )\r\n    {\r\n        perror(\"Thread\");\r\n        exit(1);\r\n    }\r\n\r\n    <span class=\"comments\">\/* prompt for your name *\/<\/span>\r\n    printf(\"What is your name? \");\r\n    fgets(buffer,BUFSIZ,stdin);\r\n    printf(\"Hello, %s\",buffer);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The <em>main()<\/em> function creates the new thread at Line 26. When an error occurs, the <em>pthread_create()<\/em> function returns a value other than zero. (It does not return -1 on error.) The global <em>errno<\/em> value is set, so the <em>perror()<\/em> function informs the user at Line 29 and the program stops. Otherwise, the user is prompted for input at Lines 33 and 34.<\/p>\n<p>At the same time, the <em>thread_funct()<\/em> executes. It outputs an asterisk at Line 13. The newline ensures that the output buffer is flushed so that you see the asterisk, which interferes with your typing. The <em>sleep()<\/em> function at Line 14 pauses execution in the thread for one second before the <em>for<\/em> loop repeats and coughs up another asterisk.<\/p>\n<p>Here is a sample run where I try typing my name as the program spits out asterisks:<\/p>\n<p><code>What is your name? *<br \/>\n*<br \/>\nDan*<br \/>\n G*<br \/>\nook*<br \/>\nin*<br \/>\n*<br \/>\nHello, Dan Gookin<\/code><\/p>\n<p>The program (and its thread) stops after I type my name. If I wait, the thread outputs its eight asterisks and then stops:<\/p>\n<p><code>What is your name? *<br \/>\n*<br \/>\n*<br \/>\n*<br \/>\n*<br \/>\n*<br \/>\n*<br \/>\n*<br \/>\nDan Gookin<br \/>\nHello, Dan Gookin<\/code><\/p>\n<p>In <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5376\">next week&#8217;s Lesson<\/a> I continue exploration of multithreaded programming.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A better approach for doing multiple things at once is to use threads in your code. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5365\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-5365","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5365","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5365"}],"version-history":[{"count":8,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5365\/revisions"}],"predecessor-version":[{"id":5398,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5365\/revisions\/5398"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5365"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5365"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5365"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}