Linux 中的线程被称为轻量级进程。无论是进程还是线程,它们都是通过task_struct数据结构来实现的。
1> 那么,从这个意义上说,内核如何区分线程和进程?
2> 当发生上下文切换时,线程如何在上下文切换中获得更少的开销?因为在此线程之前,另一个进程的另一个线程可能正在运行。因此,即使资源在进程的线程之间共享,内核也应该加载所有资源。
什么是C++中的Dynamic_cast中的side-cast/ cross-cast.有人能解释一个例子吗?
#include <iostream>
using namespace std;
class A
{
virtual void fn(){}
};
class B:public A
{
};
class C:public A
{
};
int main() {
B b;
C* c;
{
c = dynamic_cast<C*> (&b);
}
if(!c)
{
cout<<"invalid cast "<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它打印无效的演员表.那么,是什么side-cast?
class A;
class B;
class B
{
public:
void fn1(void (A::*fn)() )
{
//(*A::fn) ();how to call fn()?
}
};
class A
{
B *b;
public:
A():b(new B){}
void fn2()
{
cout<<"fn2"<<endl;
}
void fn3()
{
b->fn1(&A::fn2);
}
};
int main()
{
A a;
a.fn3();
}
Run Code Online (Sandbox Code Playgroud)
我在接受采访时被问到这个问题:如何从fn1()调用fn2().这就是我想要解决的问题.有人可以帮助我吗?我的主要目标是从fn1()调用fn2(); 如果有其他方式可以,请提及
仅在堆上创建对象-> 1> 代码中是否有任何错误
class B
{
~B(){}
public:
void Destroy()
{
delete this;
}
};
int main() {
B* b = new B();
b->Destroy();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么你不能在堆栈 2 上创建类 b 的对象>
class B
{
B(){}
public:
static B* Create()
{
return new B();
}
};
int main() {
//B S;
B* b = B::Create();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
3>如何只在栈上而不是堆上创建对象
我在面试中被问到一个问题,共享内存中是如何进行同步的。我告诉采取一个结构。你有一个标志和一个数据。测试标志并更改数据。我从互联网上获取了以下程序,如下所示-。谁能告诉共享内存中是否有更好的同步方法
#define NOT_READY -1
#define FILLED 0
#define TAKEN 1
struct Memory {
int status;
int data[4];
};
Run Code Online (Sandbox Code Playgroud)
假设服务器端和客户端都在当前目录。服务器使用 ftok() 生成密钥并使用它来请求共享内存。在共享内存充满数据之前,状态设置为 NOT_READY。共享内存填满后,服务器将状态设置为 FILLED。然后,服务器等待,直到状态变为 TAKEN,这意味着客户端已获取数据。
下面是服务器程序。单击此处下载该服务器程序 server.c 的副本。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "shm-02.h"
void main(int argc, char *argv[])
{
key_t ShmKEY;
int ShmID;
struct Memory *ShmPTR;
if (argc != 5) {
printf("Use: %s #1 #2 #3 #4\n", argv[0]);
exit(1);
}
ShmKEY = ftok(".", 'x');
ShmID = shmget(ShmKEY, sizeof(struct Memory), IPC_CREAT | 0666);
if (ShmID …Run Code Online (Sandbox Code Playgroud)