Skip to content

Instantly share code, notes, and snippets.

@rishabh-ink
Created February 3, 2018 21:59
Show Gist options
  • Save rishabh-ink/d61d3d8791166cce16370cafbf45871f to your computer and use it in GitHub Desktop.
Save rishabh-ink/d61d3d8791166cce16370cafbf45871f to your computer and use it in GitHub Desktop.
/* spinlock.cpp */
#include <pthread.h>
#include <iostream>
using namespace std;
/* create a mutex lock */
static pthread_spinlock_t echoLock;
void *echoThis(void *text)
{
/* spin until lock is acquired */
if(pthread_spin_lock(&echoLock))
{
/* error acquiring spin lock */
/* NOTE: if the lock is already acquired by another thread, then it is not an error, the thread will simply spin until the lock is acquired */
perror("pthread_spin_lock");
}
/* lock was successfully acquired */
/* ***** START OF CRITICAL SECTION ***** */
/* print the text */
cout << "TID: " << pthread_self() << "\t\tTEXT: " << (char *) text << endl << flush;
/* ***** END OF CRITICAL SECTION ***** */
/* release the lock */
if(pthread_spin_unlock(&echoLock))
{
/* error releasing lock */
perror("pthread_spin_unlock");
}
/* lock successfully released */
}
int main(int argc, char * argv[])
{
/* create as many threads as the number of command line arguments */
int maxThreads = argc - 1;
int i;
pthread_t tid;
/* initialize the spin lock */
if(pthread_spin_init(&echoLock, PTHREAD_PROCESS_PRIVATE))
{
/* error initializing lock */
perror("pthread_spin_init");
}
/* create threads which will call echoThis */
for(i = 1; i <= maxThreads; i++)
{
/* create a thread with the default properties */
if(pthread_create(&tid, NULL, echoThis, argv[i]))
{
/* error creating thread */
perror("pthread_create");
}
}
/* wait for all the threads to join */
while(!pthread_join(tid, NULL))
{
/* do nothing */
;
}
/* destroy the spin lock */
if(pthread_spin_destroy(&echoLock))
{
/* error removing the spin lock */
perror("pthread_spin_destroy");
}
return 0;
}
/* end of spinlock.cpp */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment