Created
May 18, 2010 20:56
-
-
Save afeinberg/405537 to your computer and use it in GitHub Desktop.
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 <stdio.h> | |
| #include <stdlib.h> | |
| #include <assert.h> | |
| #include <pthread.h> | |
| #include <unistd.h> | |
| static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; | |
| void *f(void *p) { | |
| long l; | |
| pthread_mutex_lock(&m); | |
| l = random(); | |
| pthread_mutex_unlock(&m); | |
| printf("Entering sleep for: %ld\n", l); | |
| sleep(l); | |
| } | |
| int main(int argc, char **argv) { | |
| int n = atoi(argv[1]); | |
| pthread_t* t = (pthread_t *) malloc(sizeof(pthread_t) * n); | |
| int i = 0; | |
| int rc; | |
| assert(t); | |
| for (i = 0; i < n; i++) { | |
| rc = pthread_create((&t[i]), NULL, f, NULL); | |
| if (rc == 0) { | |
| pthread_detach(t[i]); | |
| if (i % 100 == 0) | |
| printf("%d threads so far\n", i+1); | |
| continue; | |
| } | |
| printf("failed to create thread %d with error code %d\n", i, rc); | |
| break; | |
| } | |
| free(t); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment