在使用多线程时,需要注意线程之间的同步问题,避免出现数据竞争等情况。同时,应该使用一些工具来检查和调试多线程程序,例如使用线程安全的数据结构、锁和信号量等。
以下是一个代码示例,通过使用锁和条件变量来保证线程同步,避免未执行就退出的问题:
#include
#include
#include
pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
int count = 0;
void *decrement_count(void *t)
{
pthread_mutex_lock(&count_lock);
while (count == 0)
{
pthread_cond_wait(&count_nonzero, &count_lock);
}
count--;
printf("Thread %ld: count is %d\n", (long)t, count);
pthread_mutex_unlock(&count_lock);
return NULL;
}
void *increment_count(void *t)
{
pthread_mutex_lock(&count_lock);
count++;
printf("Thread %ld: count is %d\n", (long)t, count);
pthread_cond_signal(&count_nonzero);
pthread_mutex_unlock(&count_lock);
return NULL;
}
int main(int argc, char *argv[])
{
long t;
pthread_t threads[3];
pthread_mutex_init(&count_lock, NULL);
pthread_cond_init(&count_nonzero, NULL);
for (t = 0; t < 3; t++)
{
pthread_create(&threads[t], NULL, increment_count, (void *)t);
}
for (t = 0; t < 2; t++)
{
pthread_create(&threads[t], NULL, decrement_count, (void *)t);
}
/* Wait for all threads to complete */
for (t = 0; t < 3; t++)
{
pthread_join(threads[t], NULL);
}
pthread_mutex_destroy(&count_lock);
pthread_cond_destroy(&count_nonzero);
return 0;
}
在这个例子中,我们使用了一个计数器