Question

In: Computer Science

Generating a sequence using Pthreads Having multiple threads call a function, like will have a non-deterministic...

Generating a sequence using Pthreads

Having multiple threads call a function, like will have a non-deterministic execution. Write a program with 3 threads that call a function called do_work. Each thread will be responsible for generating a number and appending it to a buffer. Thread 1 generates number 1, thread 2 generates number 2, and thread 3 generates number 3. These numbers assigned to the threads are passed in as arguments. Each thread will store its value in a shared buffer of integers having a size of 3 elements called “buffer”. When the third element is added to the buffer by either thread 1, 2 or 3, then it checks to see if the sequence is “123”. If not, it clears the buffer and the threads try to generate the sequence again. Once the total number of sequences of “123” reach 10, the threads print out the total number of tries it took to print “123”. For example, keep track of the total number of other sequences generated (includi it should print out it’s corresponding number. Below is example output at the end of the program’s execution. Ensure that your program produces the exact same output formatting; you will see why in a moment. ...

My id: 2

My id: 1

Total ses geneted: 38

Number of cect sequences: 10

Testing:

You will test that your program appears to work correctly. I provide you with a python script that tests the output of your program: A3sequence_test.py. After you believe your pr document it as well, with screenshots and a text description. For instance “my program never stops running and it should stop because the counter value is 10 and therefore...”.

Solutions

Expert Solution

Please find the following program to check the buffer content updated by 3 different threads.

Program:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>

//buffer to hold 1,2 and 3
char buffer[3]={0,0,0};
//index to fill the buffer with 1,2, and 3
int gindex=0;

//thread function
void *do_work(void *intger)
{
char *num=(char *)intger;
//update the buffer
buffer[gindex]=*num;

//reset the buffer index
if(gindex++ == 3)
gindex=0;

return NULL;
}

int main()
{
pthread_t thread_id[3];
char a[]={'1','2','3'};
int i=0;
int totalCount = 0;
int totalThreadSpawnCount =0;

while(totalCount <= 10)
{
//spawn 3 different threads with argument passed here
for(i=0; i<=2; i++)
pthread_create(&thread_id[i], NULL, do_work, (void *)&a[i]);


//wait for three threads to join the main program
pthread_join(thread_id[0], NULL);
pthread_join(thread_id[1], NULL);
pthread_join(thread_id[2], NULL);

//check whether the buffer content is "123" and take the count
if(!strncmp(buffer, "123", 3))
{
totalCount++;
}
//increment the total try count
totalThreadSpawnCount++;

//exit the program once 10 iterations is completed.
if(totalCount==10)
{
break;
}
memset(buffer, '\0', sizeof(buffer));
}

printf("Total sequences generated: %d.\n", totalThreadSpawnCount);
printf("Number of correct sequences: %d.\n", totalCount);

exit(0);
}

Output:


USER>./a.out
Total sequences generated: 49.
Number of correct sequences: 10.
USER>

USER>./a.out
Total sequences generated: 47.
Number of correct sequences: 10.

USER>./a.out
Total sequences generated: 35.
Number of correct sequences: 10.
USER>

Screen Shot:


Related Solutions

The project will study the coordination of multiple threads using semaphores. The design should consist of...
The project will study the coordination of multiple threads using semaphores. The design should consist of two things: (1) a list of every semaphore, its purpose, and its initial value, and (2) pseudocode for each function. Code Your code should be nicely formatted with plenty of comments. The code should be easy to read, properly indented, employ good naming standards, good structure, and should correctly implement the design. Your code should match your pseudocode. Project Language/Platform This project must target...
A woman that is at risk of having a non-viable pregnancy may have to have blood...
A woman that is at risk of having a non-viable pregnancy may have to have blood draws frequently (every several days) at the beginning of her pregnancy to check for hormone levels. What hormone do you think is most likely being checked for, why? Draw a graph showing what normal levels of this hormone would look like and what hormones of a non-viable or at-risk pregnancy might look like.
Solve the following using a generating function: Elizabeth is hosting a party inviting 7 friends. She...
Solve the following using a generating function: Elizabeth is hosting a party inviting 7 friends. She bought gifts as the following: 8 teddy bears, 8 books, 5 watches. If she wants to give 16 gifts in total, where each person gets two gifts, with at least 2 teddy bears and 1 book. How many possible ways are there to choose from what she bought? Note: Don't distinguish between who gets what, just consider the 16 gifts. Please only use a...
USING PYTHON Write a program to create a number list. It will call a function to...
USING PYTHON Write a program to create a number list. It will call a function to calculate the average values in the list. Define main ():                        Declare variables and initialize them                        Create a list containing numbers (int/float)                        Call get_avg function that will return the calculated average values in the list.                                       Use a for loop to loop through the values in the list and calculate avg                        End main()
I'm having trouble printing a fibonacci sequence using pointers with malloc's to get this output. now...
I'm having trouble printing a fibonacci sequence using pointers with malloc's to get this output. now printing with pointers: 0 1 1 2 3 5 8 13 21 34 55 89 Here's my code: #include <stdio.h> #include <stdlib.h> void fib1(int a[]); void fib2(int* a); } int main() {   int arr[2] = {0,1};   int *pointer;   arr[0]=0;   arr[1]=1;   fib1(arr);      return 0; } void fib1(int a[]){   printf("printing with arrays:\n");        for(int i=0; i<6; i++){     printf("%d %d ", a[0],a[1]);     a[0] = a[0] +...
Using Python create a script called create_notes_drs.py. In the file, define and call a function called...
Using Python create a script called create_notes_drs.py. In the file, define and call a function called main that does the following: Creates a directory called CyberSecurity-Notes in the current working directory Within the CyberSecurity-Notes directory, creates 24 sub-directories (sub-folders), called Week 1, Week 2, Week 3, and so on until up through Week 24 Within each week directory, create 3 sub-directories, called Day 1, Day 2, and Day 3 Bonus Challenge: Add a conditional statement to abort the script if...
Write a C or C++ program using the fork() system call function. You will need to...
Write a C or C++ program using the fork() system call function. You will need to create 3 processes – each process will perform a simple task. Firstly, create an integer "counter" initialized to a random value between 1 and 100. Print this number to the console. This can be done by: Including the stdio.h and stdlib.h libraries Using the rand() function to generate your randomly generated number The main thread consists of the parent process. Your job is to...
Answer the following questions using the sequence given below. Non-template DNA 5’ – ATG CGT TCG...
Answer the following questions using the sequence given below. Non-template DNA 5’ – ATG CGT TCG TTA TGG CTG CTT – 3’ 1. Provide sequence of template DNA 2. Provide sequence of mRNA 3. Provide sequence of tRNA anticodon for the 3rd triplet 4. Provide the sequence of the amino acid encoded by the mRNA 5. What is the effect on the amino acid sequence as a result of each of the following mutations? substitution of T for G at...
1. What would the regression output (analysis) look like using this multiple regression equation and the...
1. What would the regression output (analysis) look like using this multiple regression equation and the following data? Daily Gross Revenue= total daily income+b1*daily tour income+b2*number of tourists+b3*Friday+b4*Saturday 2. What's the multiple regression equation with the numbers from the output? Years Weekend Daily Tour Income Number of Tourists Daily Gross Revenue Total Daily Income 1 Friday 3378 432 4838.95 8216.95 1 Saturday 1198 139 3487.78 4685.78 1 Sunday 3630 467 4371.3 8001.3 2 Friday 4550 546 6486.48 11036.48 2 Saturday...
Question I'm having trouble with: Using LISP, write a recursive function that takes a list and...
Question I'm having trouble with: Using LISP, write a recursive function that takes a list and returns the number of times the symbol 'a' occurs in it. Note: do not count a's that might occur in a sublist within the list.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT