In this chapter we will use POSIX threads (pthreads) to blink the LED.

Here is a very good reading on pthreads.

There is change in how we compile the applications. Instead of make, I will be using scons, with the hope that our application will grow and scons will provide more flexibility, and will be easier to manage.

Summary of the code:

  • Inside main:

    • Create a thread that will blink LED

    • Enter a while loop until application is aborted by user

    • Before exit, terminate the thread

  • Inside LED thread:

    • Enter a while loop that will toggle LED just like we have seen in the previous chapters.

I have refactored the code into multiple files so that it is modular and easier to maintain.

All the code can be found here: led_threads

Source code (showing only thread creation and termination):


int create_led_thread(void)
{

	int error;
	error = pthread_create(&;blink_led_thread, NULL, blink_led, NULL);
	CHECK_ERROR;

	printf("thread created\n");

	return 0;
}

void terminate_led_thread(void)
{

	void *ret_value;
	pthread_cancel(blink_led_thread);
	pthread_join(blink_led_thread, &ret_value);

	printf("thread terminated\n");

}

SConstruct:


#scons file for led using threads

import os
				  
env_options = {
    "CC"    	: "aarch64-linux-gnu-gcc",
    "CCFLAGS" 	: "-Wall -g",
    "LDFLAGS"	: "-pthread",
    "LINKFLAGS"	: "-pthread"
}

env = Environment(**env_options)
env.Append(ENV = {'PATH' : os.environ['PATH']})

env.Program('led_threads', Glob('*.c'))

 

Thread can be seen in Eclipse debug perspective as shown in screenshot below.

Thread to blink LED

 

 

References: 

 

 

Add comment


Security code
Refresh