Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _GNU_SOURCE
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <string.h>
- #include <sched.h>
- #define LINE_SIZE (1 << 12)
- int n;
- pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
- int totalCnt = 0;
- static char target;
- void *routine(void *arg) {
- char *line = (char*)arg;
- int cnt = 0, r = 0;
- for (int i = 0; line[i]; i++) {
- if (line[i] == target) {
- cnt++;
- }
- }
- if ((r = pthread_mutex_lock(&mtx)) != 0) {
- fprintf(stderr, "pthread_mutex_lock: %s\n", strerror(r));
- pthread_exit(NULL);
- }
- totalCnt += cnt;
- if ((r = pthread_mutex_unlock(&mtx)) != 0) {
- fprintf(stderr, "pthread_mutex_unlock: %s\n", strerror(r));
- pthread_exit(NULL);
- }
- return NULL;
- }
- int main(int argc, char *argv[]) {
- if (argc != 2) {
- fprintf(stderr, "WRONG USAGE!\n");
- exit(1);
- }
- target = argv[1][0];
- cpu_set_t cpuset;
- CPU_ZERO(&cpuset);
- CPU_SET(0, &cpuset);
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset);
- scanf("%d", &n);
- getchar();
- char line[n][LINE_SIZE];
- for (int i = 0; i < n; i++) {
- fgets(line[i], LINE_SIZE, stdin);
- }
- pthread_t thread[n];
- int r = 0;
- pthread_mutex_init(&mtx, NULL);
- for (int i = 0; i < n; i++) {
- if ((r = pthread_create(&thread[i], &attr, routine, line[i])) != 0) {
- fprintf(stderr, "pthread_create: %s\n", strerror(r));
- exit(1);
- }
- }
- for (int i = 0; i < n; i++) {
- if ((r = pthread_join(thread[i], NULL)) != 0) {
- fprintf(stderr, "pthread_join: %s\n", strerror(r));
- exit(1);
- }
- }
- pthread_attr_destroy(&attr);
- pthread_mutex_destroy(&mtx);
- printf("%d\n", totalCnt);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement