Monthly Archives: October 2013
C++ || Snippet – Custom Template “ToString” Function For Primitive Data Types
The following is a custom template “ToString” function which converts the value of a primitive data type (i.e: int, double, long, unsigned, char, etc.) to an std::string. So for example, if you wanted to convert an integer value to an std::string, the following function can do that for you.
This function works by accepting a primitive datatype as a function parameter, then using the std::stringstream class to convert and return an std::string object containing the representation of that incoming function parameter as a sequence of characters.
The code demonstrated on this page is different from the std::to_string function in that this implementation does not require a compiler to have >= C++11 support. This function should work on any compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
// ============================================================================ // Author: K Perkins // Date: Oct 27, 2013 // Taken From: http://programmingnotes.org/ // File: ToString.cpp // Description: Demonstrates the use of a custom "ToString" function // which converts a value of a primitive data type (int, double, long, // unsigned, char, etc.) to an std::string. // ============================================================================ #include <iostream> #include <string> #include <sstream> using namespace std; // function prototype template<typename ItemType> string ToString(const ItemType& value); int main() { // declare variables int inum = -1987; double fnum = 7.28; long lnum = 12345678910; char c = 'k'; char cstring[] = "This is a c-string"; string stdString = "This is a std::string"; // convert & save the above values to a std::string buffer string buffer = ToString(inum) + ", " + ToString(fnum) + ", " + ToString(lnum) + ", " + ToString(c) + ", " + ToString(cstring) + ", " + ToString(stdString); cout<<buffer<<endl; return 0; }// end of main /** * FUNCTION: ToString * USE: Converts and returns the parameter "value" to an std::string * @param value - An item of a primitive data type (int, double, long, unsigned, etc.) * @return - An std::string object containing the representation of "value" as * a sequence of characters. */ template<typename ItemType> string ToString(const ItemType& value) { stringstream convert; convert << value; return convert.str(); }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
-1987, 7.28, 12345678910, k, This is a c-string, This is a std::string
C++ || File Copier Using Memory Mapped Files
The following is another homework assignment which was presented in an Operating Systems Concepts class. Using commandline arguments, the following is a program which implements a file copier using memory mapped files. This program makes use of the “mmap” function call provided on Unix based systems.
REQUIRED KNOWLEDGE FOR THIS PROGRAM
How To Use Memory Mapped Files
How To Get The Size Of A File
How To Create A File Of Any Size
==== 1. OVERVIEW ====
A memory mapped file is a segment of virtual memory which has been assigned a direct byte for byte correlation with some portion of a file or file like resource. The primary benefit of memory mapping a file is increasing I/O performance, especially when used on large files. Accessing memory mapped files is faster than using direct read and write operations. Memory mapped files are designed to simplify and optimize file access.
The program demonstrated on this page works with any file type (i.e: txt, cpp, jpg, png, mp4, flv, etc.) and copies the contents of one file, and saves it into another separate output file.
==== 2. TECHNICAL DETAILS ====
This program has the following flow of control:
1. The program is invoked with the source file name and the destination file name as commandline arguments.
2. The program uses the mmap() system call to map both files into memory.
3. The program uses the memory-mapped file memory to to copy the source file to the destination file.
This program is also modified in such a way that you cannot do an mmap on the same file. For example, if you have an input file “A” as the source file, the destination file “B” needs to have a different filename. If both the source and the destination files have the same filename, an error message is displayed, and the program exits. In order for this program to work, the source and the destination files must have different names.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
// ============================================================================ // Author: K Perkins // Date: Oct 5, 2013 // Taken From: http://programmingnotes.org/ // File: Mcp.cpp // Description: This program implements a file copier based on memory // mapped files. // This program has the following flow of control: // (1) The program is invoked with the source file name and the // destination file name as parameters. // (2) The program uses the mmap() system call to map both files into // memory. // (3) The program uses the memory-mapped file memory to copy the // source file to the destination file. // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/mman.h> using namespace std; int main(int argc, char* argv[]) { // declare variables struct stat statInfo; int srcFd = -1; int destFd = -1; int pagesize = -1; int mappingSize = -1; int leftToWrite = -1; off_t offset = 0; char* srcBuff = NULL; char* destBuff = NULL; const char* srcFileName = NULL; const char* destFileName = NULL; FILE* destFp = NULL; // check if theres enough commandline args if(argc < 3) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"nUSAGE: "<<argv[0]<<" <SOURCE FILE NAME> <DESTINATION FILE NAME>nn"; exit(1); } // set the pointers to the source and destination files srcFileName = argv[1]; destFileName = argv[2]; // check if the source and the destination file have the same name if(strncmp(srcFileName, destFileName, sizeof(srcFileName)) == 0) { cerr<<"n** ERROR - The source and destination files both have the " <<"same name..nnPlease select a name other than "" <<srcFileName<<"" for the destination file!nn"; exit(1); } // get the file information if(stat(srcFileName, &statInfo) < 0) { perror("stat error"); exit(1); } // open the destination file destFp = fopen(destFileName, "w+"); // make sure it opened ok if(!destFp) { perror("open error"); exit(1); } // display info to the screen cerr<<"nThe source file ""<<srcFileName<<"" is " <<statInfo.st_size<<" bytesn"; // set the pointer to the end of the file if(fseek(destFp, statInfo.st_size - 1, SEEK_SET) < 0) { perror("fseek error"); exit(1); } // write a single byte to make the destination file // the same size as the "source" file if(fwrite("", 1, sizeof(""), destFp) < 0) { perror("write error"); exit(1); } // close the destination file fclose(destFp); // open the source file for reading srcFd = open(srcFileName, O_RDONLY); // make sure the file was opened successfully if(srcFd < 0) { perror("open error"); exit(1); } // open the destination file again, this time for actual writing destFd = open(destFileName, O_RDWR); // make sure the destination file was opened successfully if(destFd < 0) { perror("open error"); exit(1); } // get the size of the page pagesize = getpagesize(); // how many bytes left to write leftToWrite = statInfo.st_size; // copy the bytes of the source file to the destination file while(leftToWrite) { // if there is more than pagesize bytes, // then map pagesize bytes. Otherwise, // map the remaining bytes if(leftToWrite > pagesize) { mappingSize = pagesize; } else { mappingSize = leftToWrite; } //cerr<<"mappingSize = "<<mappingSize<<endl; // map the pagesized source file if((srcBuff = (char*)mmap(NULL, mappingSize, PROT_READ, MAP_SHARED, srcFd, offset)) == (void*)-1) { perror("mmap1 error"); exit(1); } // map the pagesized destination file if((destBuff = (char*)mmap(NULL, mappingSize, PROT_READ|PROT_WRITE, MAP_SHARED, destFd, offset)) == (void*)-1) { perror("mmap2 error"); exit(1); } // copy the source to destination memcpy(destBuff, srcBuff, mappingSize); // update the number of bytes left to write leftToWrite -= mappingSize; // update the offset offset += mappingSize; // unmap both buffers if(munmap((void*)srcBuff, mappingSize) < 0) { perror("munmap1 error"); exit(1); } if(munmap((void*)destBuff, mappingSize) < 0) { perror("munmap2 error"); exit(1); } } // display info to the screen cerr<<"nThe destination file "" <<destFileName<<"" has been created and is "<<offset<<" bytesnn"; // close both file descriptors close(srcFd); close(destFd); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
./mcp 1.png 2.png
The source file "1.png" is 42004 bytes
The destination file "2.png" has been created and is 42004 bytes
C++ || Snippet – How To Create A File Of Any Size
The following is sample code which demonstrates how to create a file of any size using the fseek and fwrite function calls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
// ============================================================================ // Author: K Perkins // Date: Oct 4, 2013 // Taken From: http://programmingnotes.org/ // File: createfileN.cpp // Description: Demonstrate how to create a file of any size // ============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; int main(int argc, char* argv[]) { // declare variables int fileSize = 0; FILE* fp = NULL; // check the command line arguments if(argc < 3) { cerr<<"n** ERROR NOT ENOUGH ARGS!n" <<"nUSAGE: "<<argv[0]<<" <FILE NAME> <FILE SIZE>nn"; exit(1); } // convert the file size from string to integer fileSize = atoi(argv[2]); // open the file to be created fp = fopen(argv[1], "w+"); // make sure the file was created ok if(!fp) { perror("open error"); exit(1); } // set the file marker to position N in the file (where N = file size) if(fseek(fp, fileSize - 1, SEEK_SET) < 0) { perror("fseek error"); exit(1); } // write a single byte to the file if(fwrite(" ", sizeof(char), strlen(" "), fp) < 0) { perror("write error"); exit(1); } // close the file fclose(fp); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
./createfileN createfile.txt 12
[FILE "createfile.txt" IS CREATED AND IS 12 BYTES IN SIZE]
C++ || Snippet – How To Use Memory Mapped Files
The following is sample code which demonstrates the use of the “mmap”, “munmap” and “getpagesize” function calls on Unix based systems.
A memory mapped file is a segment of virtual memory which has been assigned a direct byte for byte correlation with some portion of a file or file like resource. This resource is typically a file that is physically present on disk, but can also be a device, shared memory object, or other resource that the operating system can reference through a file descriptor.
The primary benefit of memory mapping a file is increasing I/O performance, especially when used on large files. Accessing memory mapped files is faster than using direct read and write operations for two reasons. Firstly, a system call is orders of magnitude slower than a simple change to a program’s local memory. Secondly, in most operating systems the memory region mapped actually is the kernel’s page cache (file cache), meaning that no copies need to be created in user space.
The following example demonstrates the use of the “mmap” to map a file into memory, and display its contents to the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
// ============================================================================ // Author: K Perkins // Date: Oct 4, 2013 // Taken From: http://programmingnotes.org/ // File: mmap.cpp // Description: Demonstrate the use of memory mapped files // ============================================================================ #include <iostream> #include <cstdlib> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h> using namespace std; int main(int argc, char* argv[]) { // declare variables int fd = -1; int pagesize = -1; char* data = NULL; // check if theres enough commandline args if(argc < 2) { cerr<<"USAGE: "<<argv[0]<<" <FILE NAME>n"; exit(1); } // open the specified file fd = open(argv[1], O_RDWR); // check if the open was successful if(fd < 0) { cerr<<"open error (file not found)n"; exit(1); } // get the page size pagesize = getpagesize(); // map the file into memory data = (char*)mmap((caddr_t)0, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); // did the mapping succeed ? if(!data) { cerr<<"mmap errorn"; exit(1); } // print the whole file character-by-character for(int x = 0; x < pagesize; ++x) { cerr<<data[x]; } // optional: write a string to the file //memcpy(data, "Hello world, this is a testn", sizeof("Hello world, this is a test")); // unmap the shared memory region munmap(data, pagesize); // close the file close(fd); return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
./mmap mmap.cpp
[THE CONTENTS OF "MMAP.CPP" IS DISPLAYED TO THE SCREEN]
C++ || Snippet – How To Display The Size Of A File Using Stat
The following is sample code which demonstrates the use of the “stat” function calls on Unix based systems.
The stat function returns information about a file. No permissions are required on the file itself, but-in the case of stat() and lstat() – execute (search) permission is required on all of the directories in path that lead to the file.
The “stat” system call returns a stat structure, which contains the following fields:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
struct stat { dev_t st_dev; /* ID of device containing file */ ino_t st_ino; /* inode number */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device ID (if special file) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for file system I/O */ blkcnt_t st_blocks; /* number of 512B blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */ }; |
The following example demonstrates the use of the “st_size” struct parameter to display the size of a file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
// ============================================================================ // Author: K Perkins // Date: Oct 4, 2013 // Taken From: http://programmingnotes.org/ // File: Stat.cpp // Description: Demonstrate the use of the "stat" function to display the // size of a file // ============================================================================ #include <iostream> #include <cstdlib> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> using namespace std; int main(int argc, char* argv[]) { // declare variables struct stat fileInfo; // the buffer to store file information // check to see if theres enough commandline args if(argc < 2) { cerr<<"n** ERROR - NOT ENOUGH ARGUMENTS!n" <<"nUSAGE: "<<argv[0]<<" <FILE NAME>n"; exit(1); } // get the file information if(stat(argv[1], &fileInfo) < 0) { cerr<<"nstat failed (file not found)n"; exit(1); } // display info to the screen cerr<<"nThe file ""<<argv[1]<<"" is "<<(int)fileInfo.st_size<<" bytesnn"; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
./Stat Stat.cpp
The file "Stat.cpp" is 1170 bytes
C++ || Snippet – Multi-Process Synchronization Producer Consumer Problem Using Threads
The following is sample code which demonstrates the use of POSIX threads (pthreads), aswell as pthread mutex and condition variables for use on Unix based systems.
The use of mutual exclusion (mutex) variables refers to the requirement of ensuring that no two processes or threads are in their critical section at the same time. Here, a critical section refers to the period of time in which a process accesses a shared resource, such as shared memory. This procedure highlights a classic example of a multi-process synchronization problem known as the producer–consumer problem.
The producer–consumer problem describes a scenario in which two processes (the producer and the consumer) share a common resource (i.e: a string buffer). In this scenario, the producer’s job is to generate a piece of data, update that data with the shared resource (the buffer), and repeat. At the same time, the consumer is consuming that shared resource (i.e: removing something from that same buffer) one piece at a time. The problem is to make sure that the producer wont try to manipulate that shared resource (i.e: add data into the buffer) while the consumer is accessing it; and that the consumer wont try to remove data from that shared resource (the buffer) while the producer is updating it.
In this instance, a solution for the producer can be to go to sleep if a synchronization conflict occurs, and the next time the consumer removes an item from the buffer, it can notify the producer to wake up and start to fill the buffer again. In the same way, the consumer can go to sleep when the producer is accessing it. The next time the producer puts data into the buffer, it wakes up the sleeping consumer and the process continues.
The example on this page demonstrates the use of the above solution using the “pthread_mutex_lock()” function call to limit access to the critical section, and the “pthread_cond_wait()” function call to simulate the sleeping process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
// ============================================================================ // Author: Kenneth Perkins // Date: Oct 3, 2013 // Taken From: http://programmingnotes.org/ // File: Condvar.cpp // Description: Demonstrate the use of the producer consumer problem // using mutex and condition variables // ============================================================================ #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; // Compile & Run // g++ Condvar.cpp -lpthread -o Condvar // ./Condvar // function prototypes void* Produce(void* arg); void* Consume(void* arg); // global variables // the mutex and the condition variable pthread_mutex_t mutex; pthread_cond_t cond; // the condition flag bool condition = false; // the item produced int count = 0; // how much to produce const int NUM_TO_PRODUCE = 6; int main() { // declare variables pthread_t producerThread; pthread_t consumerThread; // initialize the mutex and the condition variable pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); cout <<"\nThe Parent is creating the producer and consumer threads..\n" << endl; // create a producer thread if(pthread_create(&producerThread, NULL, Produce, NULL) < 0) { perror("pthread_create"); exit(1); } // create a consumer thread if(pthread_create(&consumerThread, NULL, Consume, NULL) < 0) { perror("pthread_create"); exit(1); } // wait for the threads to complete // similar to the wait() system call for fork() processes if(pthread_join(producerThread, NULL) < 0) { perror("pthread_join"); exit(1); } if(pthread_join(consumerThread, NULL) < 0) { perror("pthread_join"); exit(1); } cout <<"\nBoth threads have completed and have terminated!\n" <<"\nThe Parent is now exiting...\n"; return 0; }// end of main /** * The producer thread function * @param arg - pointer to the thread local data - unused */ void* Produce(void* arg) { // produce things until the loop condition is met while(count < NUM_TO_PRODUCE) { // lock the mutex to protect the condition variable if(pthread_mutex_lock(&mutex) < 0) { perror("pthread_mutex_lock"); exit(1); } // we have produced something that has not been // consumed yet, so we sleep (wait) until the consumer // wakes us up. while(condition) { // sleep (wait) on a condition variable until the // the consumer wakes the producer up. if(pthread_cond_wait(&cond, &mutex) < 0) { perror("pthread_cond_wait"); exit(1); } } // produce an item cout <<"Produced: "<<++count<<endl; // we have produced something condition = true; // wake up the sleeping consumer if(pthread_cond_signal(&cond) < 0) { perror("pthread_cond_signal"); exit(1); } // release the mutex lock if(pthread_mutex_unlock(&mutex) < 0) { perror("pthread_mutex_unlock"); exit(1); } } return 0; }// end of Produce /** * The consumer function * @param arg - pointer to the thread local data - unused */ void* Consume(void* arg) { // consume things until the loop condition is met while(count < NUM_TO_PRODUCE) { // lock the mutex to protect the condition variable if(pthread_mutex_lock(&mutex) < 0) { perror("pthread_mutex_lock"); exit(1); } // if there is nothing to consume, then sleep while(!condition) { // sleep (wait) on a condition variable until the // producer wakes the consumer up. if(pthread_cond_wait(&cond, &mutex) < 0) { perror("pthread_cond_wait"); exit(1); } } cout <<"Consumed: "<<count<<endl<<endl; // consume the item condition = false; // wake up the sleeping producer if(pthread_cond_signal(&cond) < 0) { perror("pthread_cond_signal"); exit(1); } // unlock the mutex if(pthread_mutex_unlock(&mutex) < 0) { perror("pthread_mutex_unlock"); exit(1); } } return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
To use pthreads, the compiler flag “-lpthread” must be set.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
The Parent is creating the producer and consumer threads..
Produced: 1
Consumed: 1Produced: 2
Consumed: 2Produced: 3
Consumed: 3Produced: 4
Consumed: 4Produced: 5
Consumed: 5Produced: 6
Consumed: 6Both threads have completed and have terminated!
The Parent is now exiting...
C++ || Snippet – How To Create And Use Threads For Interprocess Communication
The following is sample code which demonstrates the use of POSIX threads (pthreads), aswell as the pthread_create, and pthread_join function calls on Unix based systems.
Much like the fork() function call which is used to create new processes, threads are similar in that they too are used for interprocess communication. Threads allow for multi-threading, which is a widespread programming and execution model that allows for multiple threads to exist within the same context of a single program.
Threads share the calling parent process’ resources. Each process has it’s own address space, but the threads within the same process share that address space. Threads also share any other resources within that process. This means that it’s very easy to share data amongst threads, but it’s also easy for the threads to step on each other, which can lead to bad things.
The example on this page demonstrates the use of multiple pthreads to display shared data (an integer variable) to the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
// ============================================================================ // Author: Kenneth Perkins // Date: Oct 3, 2013 // Taken From: http://programmingnotes.org/ // File: Pthread.cpp // Description: Demonstrate the use of using multiple threads using the // pthread_create() function // ============================================================================ #include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; // Compile & Run // g++ Pthread.cpp -lpthread -o Pthread // ./Pthread <NUMBER OF THREADS TO CREATE> // function prototype void* ThreadFunc(void* args); // global variable int threadNum = 0; int main(int argc, char* argv[]) { // declare variables int numberOfThreads = 0; pthread_t* threads; // make sure theres enough commandline arguments // and EXIT if theres not if(argc < 2) { cout <<"** ERROR - NOT ENOUGH ARGS!\n" <<"\nUSAGE:"<<argv[0]<<" <NUMBER OF THREADS TO CREATE>\n"; exit(1); } // convert the number of threads from the command line // from string to int value numberOfThreads = atoi(argv[1]); // declare the array of thread variables threads = new pthread_t[numberOfThreads]; cout <<"\nThe Parent is creating "<<numberOfThreads<<" threads!" << endl; // use a loop to create the threads for(int x = 0; x < numberOfThreads; ++x) { // create the thread and call the "ThreadFunc" if(pthread_create(&threads[x], NULL, ThreadFunc, NULL) < 0) { perror("pthread_create error"); exit(1); } } cout <<"The Parent is now waiting for the thread(s) to complete...\n\n"; // wait for all threads to finish for(int x = 0; x < numberOfThreads; ++x) { pthread_join(threads[x], NULL); } cout <<"\nAll thread(s) are complete and have terminated!\n" <<"\nThe Parent is now exiting...\n"; return 0; }// end of main /** * The function called by the thread * @param args - pointer to the thread local data */ void* ThreadFunc(void* args) { // display the thread info cout <<"Hi, Im thread #"<<++threadNum <<" and this is my id number: "<<(unsigned)pthread_self()<<endl; return 0; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
So, what is the difference between fork() processes and thread processes? Threads differ from traditional multitasking operating system processes in that:
• processes are typically independent, while threads exist as subsets of a process
• processes carry considerable state information, whereas multiple threads within a process share state as well as memory and other resources
• processes have separate address spaces, whereas threads share their address space
• processes interact only through system-provided inter-process communication mechanisms.
• Context switching between threads in the same process is typically faster than context switching between processes.
To use pthreads, the compiler flag “-lpthread” must be set.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
./Pthread 5
The Parent is creating 5 threads!
The Parent is now waiting for the thread(s) to complete...Hi, Im thread #1 and this is my id number: 1664468736
Hi, Im thread #2 and this is my id number: 1647683328
Hi, Im thread #3 and this is my id number: 1656076032
Hi, Im thread #4 and this is my id number: 1672861440
Hi, Im thread #5 and this is my id number: 1681254144All thread(s) are complete and have terminated!
The Parent is now exiting...
C++ || Snippet – How To Override The Default Signal Handler (CTRL-C)
The following is sample code which demonstrates the use of the “signal” function call on Unix based systems.
Signals are interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C. The “signal” function call receives two arguments. The first argument is an integer which represents the signal number, and the second argument is a pointer to the user defined signal handling function.
The following program catches the “SIGINT” signal number using the signal() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
// ============================================================================ // Author: K Perkins // Date: Oct 3, 2013 // Taken From: http://programmingnotes.org/ // File: Signal.cpp // Description: Demonstrate the use of overriding the default signal // handler for the case when the user presses Ctrl-C. Test it by // running and pressing Ctrl-C // ============================================================================ #include <iostream> #include <csignal> #include <unistd.h> using namespace std; // function prototype void SignalHandlerFunc(int arg); // global variable int count = 10; int main() { // overide the default signal handler (CTRL-C) // with our own "SignalHandlerFunc" function signal(SIGINT, SignalHandlerFunc); cerr<<"nPlease press CTRL-Cnn"; // loop until condition is met do{ sleep(1); }while(count > 0); // press ENTER on the keyboard to end // the program once all "lives" are lost cin.get(); return 0; }// end of main /** * This function handles the signal * @param arg - the signal number */ void SignalHandlerFunc(int arg) { // display text when user presses CTRL-C if(count > 0) { cerr<<" Haha I have "<<count<<" lives!n"; } else { cerr<<" ** Ahh you got me...n"; } --count; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
Please press CTRL-C
^C Haha I have 10 lives!
^C Haha I have 9 lives!
^C Haha I have 8 lives!
^C Haha I have 7 lives!
^C Haha I have 6 lives!
^C Haha I have 5 lives!
^C Haha I have 4 lives!
^C Haha I have 3 lives!
^C Haha I have 2 lives!
^C Haha I have 1 lives!
^C ** Ahh you got me...