Last active
March 11, 2016 07:41
-
-
Save Hikari9/3c28957cc932f9c9a3bb to your computer and use it in GitHub Desktop.
Pthread CS 162 B Lab 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <cstdio> | |
| #include <cstring> | |
| #include <cstdlib> | |
| #include <algorithm> | |
| #include <pthread.h> | |
| #include <unistd.h> | |
| using namespace std; | |
| typedef void* object; | |
| int *arr; | |
| object pass_an_int(object); | |
| int main(int argc, char *argv[]) { | |
| if (argc == 1) { | |
| printf("Please pass an argument containing the thread ID.\n"); | |
| return 255; | |
| } | |
| int n = argc - 1; | |
| pthread_t *threads = new pthread_t[n]; | |
| arr = new int[n]; | |
| // create threads | |
| for (int i = 0; i < n; ++i) { | |
| arr[i] = atoi(argv[i + 1]); | |
| int error = pthread_create(threads + i, NULL, pass_an_int, reinterpret_cast<object>(i)); | |
| if (error) { | |
| printf("Thread (%d) returned error code (%d)!!!!", i, error); | |
| return 255; | |
| } | |
| } | |
| // join threads | |
| for (int i = 0; i < n; ++i) { | |
| pthread_join(threads[i], NULL); | |
| } | |
| // clean up | |
| delete[] threads, arr; | |
| return 0; | |
| } | |
| object pass_an_int(object value) { | |
| int X = *(int*) &value; | |
| int old = arr[X]; | |
| arr[X] *= (X % 2 ? -1 : old * old); | |
| printf("%d(old) has been replaced with %d(new)\n", old, arr[X]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment