我编写了以下代码来演示同一进程的2个线程之间的竞争条件.
`
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int c = 0;
void *fnC()
{
int i;
for(i=0;i<10;i++)
{
c++;
printf(" %d", c);
}
}
int main()
{
int rt1, rt2;
pthread_t t1, t2;
/* Create two threads */
if( (rt1=pthread_create( &t1, NULL, &fnC, NULL)) )
printf("Thread creation failed: %d\n", rt1);
if( (rt2=pthread_create( &t2, NULL, &fnC, NULL)) )
printf("Thread creation failed: %d\n", rt2);
/* Wait for both threads to finish */
pthread_join( t1, NULL);
pthread_join( t2, NULL);
printf ("\n");
return …Run Code Online (Sandbox Code Playgroud) 这里的目标是捕获SIGINT以关闭小型套接字服务器上的服务器套接字.我试图使用嵌套函数来保持代码清洁.但...
当我做Ctrl-C(SIGINT,对吗?)时,我明白了Illegal instruction: 4.阅读这篇文章后,我已经尝试添加-mmacosx-version-min=10.8到编译标志,因为我在10.8.执行Ctrl-C时出现相同的错误.
这里有两个问题:为什么我会得到"非法指令4"?如何在不使用全局变量的情况下关闭服务器套接字?
我的软件:
Mac OSX 10.8.4
GCC 4.2.1
Run Code Online (Sandbox Code Playgroud)
这是我正在编译的方式:
gcc -fnested-functions main.c
Run Code Online (Sandbox Code Playgroud)
这是代码:
#include <sys/socket.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void register_sigint_handler(int *serverSocket)
{
void sigint_handler(int signal) {
printf("Shutting down...\n");
printf("Server socket was %d\n", *serverSocket);
close(*serverSocket);
exit(0);
}
signal(SIGINT, &sigint_handler);
}
int main(void) {
int serverSocket = 0, guestSocket = 0;
register_sigint_handler(&serverSocket);
serverSocket = socket(PF_INET, SOCK_STREAM, 0);
while (1) {}
close(serverSocket);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 嗨我最近用以下骨架编写了一个代码:
variable;
callback(){
//variable updated here
}
thread_function(){
//variable used
}
main(){
//callback registered
//thread registered
}
Run Code Online (Sandbox Code Playgroud)
我发现无论何时variable在回调时更新,它都会在线程中自动更新,而不会将其声明variable为volatile.好吧,我不清楚它是如何管理的.先感谢您.之间,从使用代码编译的库中调用callback().
寄存器和易失性有什么区别?什么时候使用哪一个?易失性寄存器变量的含义是什么?
register int a;
volatile int a;
我现在有一些代码希望在Teensy 3.6微控制器上的基于计时器的中断中运行。该代码访问类的[global]对象数组。我已经将该数组和所有成员变量标记为volatile,我认为这是正确处理中断的第一步。
我标记为volatile的成员变量之一是std :: bitset,我想称其为非易失性方法,我不能这样做
"passing 'volatile std::bitset<16u>' as 'this' argument discards qualifiers [-fpermissive]"
Run Code Online (Sandbox Code Playgroud)
我想我可以复制位集库并将所有内容切换为volatile,但是我认为这不是必需的,所以我认为有更好的解决方案,或者我在错误地考虑问题。
请让我知道应该怎么做。
这些答案似乎建议在ISR和多线程程序中访问ISR中的全局变量时使用volatile: C'Volatile'关键字?,
在中断例程中使用C ++对象(和volatile)的正确方法是什么?,
这是许多建议使用的外部资源的补充。也许我的原始信息不清楚,或者我的情况与此不同。