我写道:
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int globalVarX;
void *threadFunction (void *arg)
{
pthread_mutex_lock (&mutex1);
while (globalVarX < 1000)
{
printf("x increment by thread id: %d", gettid ());
++globalVarX;
}
pthread_mutex_unlock (&mutex1);
return NULL;
}
int main()
{
pthread_t threadA;
pthread_t threadB;
if (pthread_create (&threadA, NULL, threadFunction, NULL))
{
fprintf (stderr, "Error creating thread\n");
return 1;
}
if (pthread_create (&threadB, NULL, threadFunction, NULL))
{
fprintf (stderr, "Error creating thread\n");
return 1;
}
if (pthread_join (threadA, NULL))
{
fprintf (stderr, "Error joining thread\n");
return 2;
}
if (pthread_join (threadB, NULL))
{
fprintf (stderr, "Error joining thread\n");
return 2;
}
return 0;
}
我得到的指纹如下:
~/studies$ ./a.out
x increment by thread id: 3154
x increment by thread id: 3154
x increment by thread id: 3154
x increment by thread id: 3154
x increment by thread id: 3154
x increment by thread id: 3154
x increment by thread id: 3154
x increment by thread id: 3154
x increment by thread id: 3154
x increment by thread id: 3154
~/studies$
另一条线的指纹没有显示。
最佳答案
第一个线程将globalVarX
增加到1000
,而第二个线程则无需执行任何操作。
我建议:
锁定一个增量而不是整个循环。
通过调用sched_yield()
,因为如果一个线程在其时间片中从globalVarX
递增到1000
,那么第二个线程仍然没有打印。
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <unistd.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int globalVarX;
void *threadFunction (void *arg)
{
int flagbreak = 0;
for(;!flagbreak;) {
pthread_mutex_lock (&mutex1);
if (globalVarX >= 1000) flagbreak = 1;
else {
++globalVarX;
printf("x increment by thread id: %ld\n", syscall(SYS_gettid));
}
pthread_mutex_unlock (&mutex1);
sched_yield();
}
return NULL;
}
int main(void)
{
pthread_t threadA;
pthread_t threadB;
if (pthread_create (&threadA, NULL, threadFunction, NULL))
{
fprintf (stderr, "Error creating thread\n");
return 1;
}
if (pthread_create (&threadB, NULL, threadFunction, NULL))
{
fprintf (stderr, "Error creating thread\n");
return 1;
}
if (pthread_join (threadA, NULL))
{
fprintf (stderr, "Error joining thread\n");
return 2;
}
if (pthread_join (threadB, NULL))
{
fprintf (stderr, "Error joining thread\n");
return 2;
}
return 0;
}
关于c - 从第二个线程不打印-带互斥锁的pthreads,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30692896/