Note that there are some explanatory texts on larger screens.

plurals
  1. POpthreads_setaffinity_np: Invalid argument?
    text
    copied!<p>I've managed to get my pthreads program sort of working. Basically I am trying to manually set the affinity of 4 threads such that thread 1 runs on CPU 1, thread 2 runs on CPU 2, thread 3 runs on CPU 3, and thread 4 runs on CPU 4.</p> <p>After compiling, my code works for a few threads but not others (seems like thread 1 never works) but running the same compiled program a couple of different times gives me different results.</p> <p>For example:<br> hao@Gorax:~/Desktop$ ./a.out<br> Thread 3 is running on CPU 3<br> pthread_setaffinity_np: Invalid argument<br> Thread Thread 2 is running on CPU 2<br> hao@Gorax:~/Desktop$ ./a.out<br> Thread 2 is running on CPU 2<br> pthread_setaffinity_np: Invalid argument<br> pthread_setaffinity_np: Invalid argument<br> Thread 3 is running on CPU 3<br> Thread 3 is running on CPU 3<br> hao@Gorax:~/Desktop$ ./a.out<br> Thread 2 is running on CPU 2<br> pthread_setaffinity_np: Invalid argument<br> Thread 4 is running on CPU 4<br> Thread 4 is running on CPU 4<br> hao@Gorax:~/Desktop$ ./a.out<br> pthread_setaffinity_np: Invalid argument </p> <p>My question is "Why does this happen? Also, why does the message sometimes print twice?"</p> <p>Here is the code:</p> <pre><code>#define _GNU_SOURCE #include &lt;stdio.h&gt; #include &lt;pthread.h&gt; #include &lt;stdlib.h&gt; #include &lt;sched.h&gt; #include &lt;errno.h&gt; #define handle_error_en(en, msg) \ do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) void *thread_function(char *message) { int s, j, number; pthread_t thread; cpu_set_t cpuset; number = (int)message; thread = pthread_self(); CPU_SET(number, &amp;cpuset); s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &amp;cpuset); if (s != 0) { handle_error_en(s, "pthread_setaffinity_np"); } printf("Thread %d is running on CPU %d\n", number, sched_getcpu()); exit(EXIT_SUCCESS); } int main() { pthread_t thread1, thread2, thread3, thread4; int thread1Num = 1; int thread2Num = 2; int thread3Num = 3; int thread4Num = 4; int thread1Create, thread2Create, thread3Create, thread4Create, i, temp; thread1Create = pthread_create(&amp;thread1, NULL, (void *)thread_function, (char *)thread1Num); thread2Create = pthread_create(&amp;thread2, NULL, (void *)thread_function, (char *)thread2Num); thread3Create = pthread_create(&amp;thread3, NULL, (void *)thread_function, (char *)thread3Num); thread4Create = pthread_create(&amp;thread4, NULL, (void *)thread_function, (char *)thread4Num); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload