#include
#include
void *thread_function(void *dummyPtr)
{
printf("Thread number %ld\n", pthread_self());
}
int main(int argc, char *argv[])
{
pthread_t thread_id;
pthread_create( &thread_id, NULL, thread_function, NULL );
pthread_join( thread_id, NULL);
printf("Final counter value: %d\n", counter);
return 0;
}
linuxthead:main.o
g++ -g -o linuxthread main.o -L. -lpthread -lrt
main.o:main.cpp
g++ -g -c main.cpp -o main.o
clean:
rm -f *.o linuxthead
pthread_mutex_t mutex; //互斥量声明
int g_counter = 0; //互斥量保护的全局变量
pthread_mutex_init(&mutex, NULL);
使用:
pthread_mutex_lock( &mutex1 );
g_counter++;
pthread_mutex_unlock( &mutex1 )
#include
#include
pthread_mutex_t mutex; //互斥量声明
int counter = 0; //互斥量保护的全局变量
void *thread_function(void *dummyPtr)
{
printf("Thread number %ld\n", pthread_self());
pthread_mutex_lock( &mutex1 );
counter++;
pthread_mutex_unlock( &mutex1 );
}
int main(int argc, char *argv[])
{
pthread_t thread_id[10];
int i, j;
pthread_mutex_init(&mutex, NULL);
for(i=0; i < 10; i++)
{
pthread_create( &thread_id[i], NULL, thread_function, NULL );
}
for(j=0; j < 10; j++)
{
pthread_join( thread_id[j], NULL);
}
printf("Final counter value: %d\n", counter);
return 0;
}
#include
#include
#include
#include
pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
unsigned count = 0;
decrement_count ()
{
pthread_mutex_lock (&count_lock);
while(count==0)
pthread_cond_wait( &count_nonzero, &count_lock);
count=count -1;
pthread_mutex_unlock (&count_lock);
}
increment_count()
{
pthread_mutex_lock(&count_lock);
if(count==0)
pthread_cond_signal(&count_nonzero);
count=count+1;
pthread_mutex_unlock(&count_lock);
}
int main(int argc, char* argv[])
{
pthread_mutex_init(&count_lock, NULL);
pthread_cond_init(&count_nonzero, NULL);
pthread_t p1, p2;
pthread_create(&p1, NULL, decrement_count, NULL);
pthread_create(&p2, NULL, increment_count, NULL);
pthread_join( p1, NULL);
pthread_join( p2, NULL);
}
overpass:main.o
g++ -g -o overpass main.o -L. -lhiredis -lpthread -lcurl -lrt -lcrypto -lidn -lssl
main.o:main.cpp
g++ -g -c main.cpp -o main.o
clean:
rm -f *.o overpass